这是一个完整的例子。
Model:
public class MyViewModel
{
public int Year { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable.Range(1980, 40).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
public IList<TheData> Data { get; set; }
}
public class TheData
{
public int Year { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(int year)
{
var model = new[]
{
new TheData { Year = year, Foo = "foo 1", Bar = "bar 1" },
new TheData { Year = year, Foo = "foo 2", Bar = "bar 2" },
new TheData { Year = year, Foo = "foo 3", Bar = "bar 3" },
};
return PartialView("_data", model);
}
}
Index.cshtml
view:
@model MyViewModel
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#yearsddl').change(function () {
$(this).closest('form').trigger('submit');
});
});
</script>
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "data" }))
{
@Html.DropDownListFor(x => x.Year, Model.Years, new { id = "yearsddl" })
}
<table>
<thead>
<tr>
<th>Year</th>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody id="data">
@Html.Partial("_data", Model.Data ?? Enumerable.Empty<TheData>())
</tbody>
</table>
The jquery.unobtrusive-ajax.js
例如,脚本包含应移出布局内的索引视图,并且订阅下拉列表更改事件的自定义 js 应移至单独的 js 文件中并从布局中包含。我只是将它们放在这里来说明视图工作所需的完整示例。
_Data.cshtml
部分的:
@model IList<TheData>
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(x => x[i].Year)</td>
<td>@Html.DisplayFor(x => x[i].Foo)</td>
<td>@Html.DisplayFor(x => x[i].Bar)</td>
</tr>
}