Здравствуйте, господа.
Может кто уже с этим сталкивался, у меня такая проблема:
хочу реализовать paging+поиск.
У меня есть view, которое выводит все записи из бд + на этом же представлении есть поиск:
view source
print?
<% using (Html.BeginForm())
{ %>
<div id="divsearch">
<%= Html.ValidationSummary("Параметры поиска заполнены не корректно") %>
<table id="tablesearch">
<tr>
<td>
Район:
</td>
<td>
<%
foreach (Area a in (IEnumerable<Area>)ViewData["Areas"])
{ %>
<%= Html.CheckBox("Area" + a.AreaId, true)%>
<label for="Areas">
<%= a.AreaName%></label>
<br />
<% } %>
</td>
<td>
Количество
<br />
комнат:
</td>
<td>
<%
foreach (Room r in (IEnumerable<Room>)ViewData["Rooms"])
{ %>
<%= Html.CheckBox("Room" + r.RoomId, true)%>
<label for="Rooms">
<%= r.RoomName%></label>
<br />
<% } %>
</td>
<td>
Цена от:
<br />
<%= Html.TextBox("LowerPrice")%>
<%= Html.ValidationMessage("LowerPrice")%>
<br />
до
<br />
<%= Html.TextBox("UpperPrice")%>
<%= Html.ValidationMessage("UpperPrice") %>
<br />
<input type="submit" value="Поиск >" class="butsearch" />
</td>
</tr>
</table>
</div>
<% } %>
<table id="tablelist">
....
</table>
<%= Html.PagerLinks("Flat", "List", (int)ViewData["TotalPages"], (int)ViewData["Page"], "pager", "pager2", "selectpager")%>
Внизу хелпер, код которого приведен ниже:
view source
print?
public static class PagerHelper
{
public static string PagerLinks(this HtmlHelper htmlHelper, string controllerName, string actionName, int pageCount, int pageIndex, string cssClass, string moreTextCssClass, string currentPageCssClass)
{
return PagerLinks(htmlHelper, controllerName, actionName, pageCount, pageIndex, "Первая", "Предыдущая", "Следующая", "Последняя", "Страницы:", cssClass, moreTextCssClass, currentPageCssClass);
}
public static string PagerLinks(this HtmlHelper htmlHelper, string controllerName, string actionName, int pageCount, int pageIndex, string firstPage, string previousPage, string nextPage, string lastPage, string moreText, string cssClass, string moreTextCssClass, string currentPageCssClass)
{
var builder = new StringBuilder();
if (String.IsNullOrEmpty(controllerName) || String.IsNullOrEmpty(actionName))
throw new Exception("controllerName and actionName must be specified for PageLinks.");
if (pageCount <= 1)
return String.Empty;
if (String.IsNullOrEmpty(cssClass)) builder.Append("<div>");
else builder.Append(String.Format("<div class=\"{0}\">", cssClass));
if (String.IsNullOrEmpty(moreTextCssClass)) builder.Append(moreText);
else builder.Append(String.Format("<span class=\"{0}\">{1}</span>", moreTextCssClass, moreText));
if (pageIndex != 1)
{
// first page link
builder.Append(htmlHelper.RouteLink("|<", new { controller = controllerName, action = actionName, id = 1 }, new { title = firstPage }));
if (pageIndex > 2)
{
// previous page link
int previousLink = pageIndex - 1;
builder.Append(htmlHelper.RouteLink("<<", new { controller = controllerName, action = actionName, id = previousLink }, new { title = previousPage }));
}
}
// calc low and high limits for numeric links
int intLow = pageIndex - 1;
int intHigh = pageIndex + 3;
if (intLow < 1) intLow = 1;
if (intHigh > pageCount) intHigh = pageCount;
if (intHigh - intLow < 5) while ((intHigh < intLow + 4) && intHigh < pageCount) intHigh++;
if (intHigh - intLow < 5) while ((intLow > intHigh - 4) && intLow > 1) intLow--;
for (int x = intLow; x < intHigh + 1; x++)
{
// numeric links
if (x == pageIndex)
{
if (String.IsNullOrEmpty(currentPageCssClass))
builder.Append(String.Format("{0} of {1}", x, pageCount));
//else builder.Append(String.Format("<span class=\"{0}\">{1} of {2}</span>", currentPageCssClass, x, pageCount));
else builder.Append(String.Format("<span class=\"{0}\">{1}</span>", currentPageCssClass, x));
}
else
{
builder.Append(htmlHelper.RouteLink(x.ToString(), new { controller = controllerName, action = actionName, id = x }));
}
}
if (pageIndex != pageCount)
{
if (pageIndex < pageCount - 1)
{
// next page link
int nextLink = pageIndex + 1;
builder.Append(htmlHelper.RouteLink(">>", new { controller = controllerName, action = actionName, id = nextLink }, new { title = nextPage }));
}
// last page link
builder.Append(htmlHelper.RouteLink(">|", new { controller = controllerName, action = actionName, id = pageCount }, new { title = lastPage }));
}
builder.Append("</div>");
return builder.ToString();
}
}
Код контроллера, для навигации по страницам хелпера (id - номер текущей страницы):
view source
print?
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult List(int? id)
{
int TotalCount;
int PageSize = 5; //количество записей на 1 странице
ViewData["Flats"] = _dataManager.Flats.GetFlats(PageSize * (id-1), PageSize, out TotalCount);
ViewData["TotalPages"] = (int)Math.Ceiling(TotalCount / (double)PageSize);
ViewData["Page"] = id ?? 0;
ViewData["Areas"] = _dataManager.Areas.GetAreas();
ViewData["Rooms"] = _dataManager.Rooms.GetRooms();
return View();
}
При нажатии на кнопку поиск:
view source
print?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult List(int? id, bool? Area1, bool? Area2, bool? Area3, ....
string LowerPrice, string UpperPrice)
{
...
ViewData["Areas"] = _dataManager.Areas.GetAreas();
ViewData["Rooms"] = _dataManager.Rooms.GetRooms();
try
{
int lprice=int.MinValue; int uprice=int.MaxValue;
if (LowerPrice != "") lprice = int.Parse(LowerPrice);
if (UpperPrice != "") uprice = int.Parse(UpperPrice);
ViewData["Flats"] = _dataManager.Flats.SelectFlats(tempAreas, tempRooms, lprice, uprice);
return View();
}
catch
{
ModelState.AddModelError("_FORM", "Цена не корректна");
ViewData["Flats"] = _dataManager.Flats.SelectFlats(tempAreas, tempRooms, int.MinValue, int.MaxValue);
return View();
}
}
На этом этапе paging уже нормально работает, но пока без поиска.
Чтобы заработал paging и поиск я попробовал объединить эти две функции в одну:
view source
print?
public ActionResult List(int? id, bool? Area1, bool? Area2, bool? Area3, ...
string LowerPrice, string UpperPrice)
{
...
ViewData["Areas"] = _dataManager.Areas.GetAreas();
ViewData["Rooms"] = _dataManager.Rooms.GetRooms();
int TotalCount;
int PageSize = 5; //количество записей на 1 странице
try
{
int lprice=int.MinValue; int uprice=int.MaxValue;
if (LowerPrice != "") lprice = int.Parse(LowerPrice);
if (UpperPrice != "") uprice = int.Parse(UpperPrice);
ViewData["Flats"] = _dataManager.Flats.SelectFlats(tempAreas, tempRooms, lprice, uprice, PageSize * (id-1), PageSize, out TotalCount);
ViewData["TotalPages"] = (int)Math.Ceiling(TotalCount / (double)PageSize);
ViewData["Page"] = id ?? 0;
return View();
}
catch
{
ModelState.AddModelError("_FORM", "Цена не корректна");
ViewData["Flats"] = _dataManager.Flats.SelectFlats(tempAreas, tempRooms, int.MinValue, int.MaxValue, PageSize * (id-1), PageSize, out TotalCount);
ViewData["TotalPages"] = (int)Math.Ceiling(TotalCount / (double)PageSize);
ViewData["Page"] = id ?? 0;
return View();
}
}
Так вот хелпер при навигации после нажатия кнопки поиска не работает (все передаваемые параметры равны null). Как правильно передавать параметры при навигации по страницам хелпера?
Или может есть совсем другие способы реализации?
Буду очень благодарен любым советам.