2012-06-11 3 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

아 하, 감사합니다! –

관련 문제