2012-06-11 98 views
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> 
} 

回答

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,否則他們不是控制器操作。

+0

啊哈,謝謝! –