有一个非常简单的博客Post创建者,我正在尝试检查Post的名称是否已经使用。 Ajax正确回发,但页面不允许我提交,也不会抛出任何错误。如果我在Create()动作中设置断点,它们永远不会被击中。
型号:
public class Post
{
public int Id { get; set; }
[Required]
[Remote("CheckPostName","Home")]
public string Name { get; set; }
[Required]
public string Author { get; set; }
public DateTime Date { get; set; }
[StringLength(400)]
public string Content { get; set; }
}
Ajax行动:
public bool CheckPostName(string Name)
{
bool result = db.Posts.Where(a => a.Name.Equals(Name)).Count() == 0;
return result;
}
提交操作:
[HttpPost]
public ActionResult Create(Post thePost)
{
if (ModelState.IsValid)
{
db.Posts.Add(thePost);
db.SaveChanges();
return View();
}
return View(thePost);
}
和视图:
@using (Html.BeginForm()) {
@Html.ValidationSummary()
<fieldset>
<legend>Post</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Author)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Author)
@Html.ValidationMessageFor(model => model.Author)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
答案 0 :(得分:2)
确保从应该验证数据的AJAX控制器操作返回JSON:
public ActionResult CheckPostName(string Name)
{
bool result = db.Posts.Where(a => a.Name.Equals(Name)).Count() == 0;
return Json(result, JsonRequestBehavior.AllowGet);
}
请记住:控制器操作必须始终返回ActionResult,否则它们不是控制器操作。