【问题标题】:Remote Attribute not allowing Post远程属性不允许发布
【发布时间】:2012-06-11 03:14:28
【问题描述】:

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

【问题讨论】:

    标签: .net asp.net-mvc-3 linq asp.net-ajax


    【解决方案1】:

    确保从应该验证数据的 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,否则它们不是控制器动作。

    【讨论】:

      猜你喜欢
      • 2014-05-23
      • 2013-01-15
      • 2015-11-25
      • 2013-06-02
      • 2014-03-07
      • 2015-08-03
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      相关资源
      最近更新 更多