试着使用ajax结合分部视图做了一个异步刷新,记录一下。
显示数据的视图代码:
<p>
@using (Ajax.BeginForm("SearchIndex", "TestDataDB", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "result"}, new { id = "searchForm" } ))
{
<p>用户名:@Html.TextBox("SearchString")<br />
<input type="submit" value="查询"/></p>
}
</p>
<table id="result">
<tr>
<th>
@Html.DisplayNameFor(model => model.Uid)
</th>
<th>
@Html.DisplayNameFor(model => model.Uname)
</th>
<th>
@Html.DisplayNameFor(model => model.Upwd)
</th>
<th>
@Html.DisplayNameFor(model => model.Udata)
</th>
<th></th>
</tr>
@{Html.RenderPartial("UserList",Model);}
</table>
分部视图UserList代码:
@foreach (Test13.Models.TestDataDB item in Model)
{
<tr>
<td>@item.Uid</td>
<td>@item.Uname</td>
<td>@item.Upwd</td>
<td>@item.Udata</td>
<td>
@Html.ActionLink("编辑", "Edit", new { id=item.ID }) |
@Html.ActionLink("查看详细", "Details", new { id=item.ID }) |
@Html.ActionLink("删除", "Delete", new { id=item.ID })
</td>
</tr>
}
控制器代码:
<span style="white-space:pre"> </span>[HttpPost]
public PartialViewResult SearchIndex(string searchString)
{
var UserData = from m in db.TestDataDBS
select m;
if (!String.IsNullOrEmpty(searchString))
{
UserData = UserData.Where(s => s.Uname.Contains(searchString));
}
return PartialView("UserList", UserData.ToList());
}
需要注意的有两点:
1、没有进行查询的时候,数据的显示也是通过分部视图。
2、Ajax.BeginForm中的UpdateTargetId表示要更新的内容,需要与页面中的元素对应。