【发布时间】:2015-03-21 13:52:20
【问题描述】:
在我看来,我可以使用Ajax.BeginForm 过滤显示的数据,它返回部分视图并仅刷新包含数据的表格。使用Ajax.ActionLink 单击列标题时,我还可以按列排序。问题是,当我使用Ajax.ActionLink 时,我必须刷新整个页面,并且我会丢失过滤器中选择的内容(它们是自定义多选组合控件),因此整个数据都会被排序和显示。
我尝试使用ViewBag 发送 Json 数据来设置过滤器,但我失败了。即使在排序时,我也宁愿只刷新表格。我对 MVC 有点陌生。
如何以一种好的方式做到这一点?感谢您的帮助!
查看:
@using (Ajax.BeginForm(new AjaxOptions() {HttpMethod = "get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "exposureRecords"}))
{
<div class="form-group">
<select id="brands-select" name="brands" multiple="multiple">
@{
var brands = Model.Brands;
foreach (var item in brands)
{
<option value="@item">@item</option>
}
}
</select>
</div>
(...similar for 3 other filters...)
<table class="table">
<tr>
<th>
@Html.ActionLink("Marka", "Index", new { sortOrder = ViewBag.BrandSortParam })
</th>
<th>
@Html.ActionLink("Dyscyplina", "Index", new { sortOrder = ViewBag.DisciplineSortParm })
</th>
<th>
@Html.ActionLink("Miesiąc", "Index", new { sortOrder = ViewBag.MonthSortParm })
</th>
<th>
@Html.ActionLink("Liczba ekspozycji", "Index", new { sortOrder = ViewBag.QuantitySortParm })
</th>
<th>
@Html.ActionLink("Ekwiwalent reklamowy", "Index", new { sortOrder = ViewBag.ValueSortParm })
</th>
</tr>
</table>
}
@Html.Partial("_Table",Model)
然后在控制器中我有
public ActionResult Index(IEnumerable<string> brands, IEnumerable<string> disciplines,
IEnumerable<string> months,string sortOrder)
{
ViewBag.BrandSortParam = String.IsNullOrEmpty(sortOrder) ? "brand_desc" : "";
ViewBag.DisciplineSortParm = sortOrder == "discipline" ? "discipline_desc" : "discipline";
ViewBag.MonthSortParm = sortOrder == "month" ? "month_desc" : "month";
ViewBag.QuantitySortParm = sortOrder == "quantity" ? "quantity_desc" : "quantity";
ViewBag.ValueSortParm = sortOrder == "value" ? "value_desc" : "value";
model.ExposureRecords = FilterExposure(brands, disciplines, months);
model.ExposureRecords = Sort(sortOrder, model.ExposureRecords);
if (Request.IsAjaxRequest())
return PartialView("_Table", model);
return View(model);
}
【问题讨论】:
-
一种方法是在服务器端呈现视图并在模型的属性中返回标记。您的链接需要更新与您的模型属性相关的隐藏字段以保存您的排序,然后调用表单的提交来触发您的 AjaxForm。您必须通过将 Model.HtmlMarkup 注入标记或其他内容来显示您对 AjaxForms.Success 的看法。我知道您想使用 Action Link 进行排序,但也许您可以通过在客户端使用 jQuery 进行排序来提高标准?签出:tablesorter.com/docs谢谢!我没有考虑过。这也解决了我的其他问题。
标签: javascript c# asp.net-mvc asp.net-mvc-5 asp.net-ajax