0

有一个非常简单的博客帖子创建者,我正在尝试检查帖子的名称是否已经在使用中。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; }
}

阿贾克斯行动:

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>
}
4

1 回答 1

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,否则它们不是控制器动作。

于 2012-06-11T04:56:46.730 回答