【发布时间】:2014-01-07 05:37:29
【问题描述】:
我是 ASP.Net MVC 的新手..
问题来了……
我有一个列出所有过滤器类型的视图。在同一个视图中..我需要一个基于 AJAX 的搜索选项。我得到了ajax部分的工作。但是如何使 Ajax 帖子针对 UserEnity 模型进行验证?是否可以将视图的 Ajax 部分移动到 partialView ?
非常感谢任何帮助。
这里是示例
@model IEnumerable<UserEntity>
@using (Ajax.BeginForm("Index", "FiltrationType", new AjaxOptions
{
HttpMethod = "post",
UpdateTargetId = "gridContent",
InsertionMode = InsertionMode.Replace }))
{
@Html.AntiForgeryToken();
@Html.ValidationSummary(true)
<p> <b>Search Filter Type </b> @Html.TextBox("SearchString") <br />
<input type="submit" name="cmdFiltrationSearch" value="Search" />
<input type="submit" name="cmdFiltrationClear" value="Clear" onclick="ClearFiltrationTypeSearchText()" />
</p>
}
<div id="gridContent">
@if (ViewBag.DataRetriveStatus != null )
{
<span class ="ErrorDiv"> @ViewBag.DataRetriveStatus </span><br />
}
else
{
@Html.Partial("_filtrationGrid", Model)
}
</div>
好消息是,在链接表单名称以匹配模型实体名称之后,我无法发布模型数据。
@using (Ajax.BeginForm("Index", "User", new AjaxOptions
{
HttpMethod = "post",
UpdateTargetId = "gridContent",
InsertionMode = InsertionMode.Replace })) {
@Html.AntiForgeryToken();
@Html.ValidationSummary(true)
<table class ="UserSearch">
<tr>
<th> Account </th>
<td>@Html.TextBox("DisplayName")
</td>
</tr>
<tr>
<th> First Name</th>
<td>@Html.TextBox("FirstName") </td>
</tr>
<tr>
<th> Last Name </th>
<td>@Html.TextBox("LastName") </td>
</tr>
</table>
<p>
<input type="submit" name="cmdUserSearch" value="Search" />
<input type="submit" name="cmdUserClear" value="Clear" onclick="ClearUserSearchText()" />
</p>
}
但是 jquery 验证在表单上不起作用..知道为什么吗?但是在控制器中验证为ModelState.IsValid 工作正常。
这是我的实体模型
public class UserSearch
{
[Required(ErrorMessage = "Display Name is Required")]
[StringLength(30, MinimumLength = 2, ErrorMessage = "Display Name length should be between 2 and 30 characters")]
[Display(Name = "Display Name")]
public string DisplayName { get; set; }
[Required(ErrorMessage = "First Name is Required")]
[StringLength(30, MinimumLength = 2, ErrorMessage = "First Name length should be between 2 and 30 characters")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is Required")]
[StringLength(30, MinimumLength = 2, ErrorMessage = "Last Name length should be between 2 and 30 characters")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
和控制器代码...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(string cmdUserSearch, string cmdUserClear, UserSearch entity)
{
if (ModelState.IsValid)
{
// some code
}
}
【问题讨论】:
-
也许您可以发布您的控制器代码?您在这里提交的唯一内容似乎是一个字符串变量
SearchString,您要绑定哪种模型? -
感谢您的回复。我想绑定 UserEntity 模型。这是我的示例控制器 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(string cmdFiltrationSearch, string cmdFiltrationClear, string SearchString, UserEntity entity) { }当我调试时..实体值为空。
-
您也可以发布您的实体模型吗?
-
我刚刚更新了我的帖子,提供了更多信息。感谢您的入住,期待您的帮助。
-
我已经更新了答案。请检查 - 我已经在一个示例项目中尝试过这个 - 使用我认为您正在使用的 MVC 4 运行良好。
标签: c# ajax asp.net-mvc model