2012-09-10 4 views
2

ASP.NET MVC 4에서 작업 중이며 모델 유효성 검사가 올바르게 작동하지 않는 문제가 있습니다.mvc 모델 유효성 검사가 모든 필드에서 작동하지 않아야합니다.

[HttpPost] 
     public ActionResult Add(MovieModel model) 
     { 
      if(ModelState.IsValid) 
      { 
       return RedirectToAction("Index"); 
      } 
      return View(); 
     } 
: 어떤 이유로 모든 내 필수 필드가 기입 할 필요가 여기에

내 모델의 :. 여기
public class MovieModel 
    { 
     public int Id { get; set; } 
     [Required] 
     public string Name { get; set; } 
     public DateTime ReleaseDate { get; set; } 
     [Required] 
     public string Genre { get; set; } 
     [Required] 
     public decimal Price { get; set; } 

     public virtual ICollection<RoleInMovie> RoleInMovie { get; set; } 
    } 

이 뷰의 내 행동 여기

@using (Html.BeginForm()) 
{ 
    <table> 
     <tr> 
      <td> 
       <label>Name:</label></td> 
      <td>@Html.EditorFor(m => m.Name)</td> 
      <td>@Html.ValidationMessageFor(m => m.Name)</td> 
     </tr> 
     <tr> 
      <td> 
       <label>Genre:</label></td> 
      <td>@Html.EditorFor(m => m.Genre)</td> 
      <td>@Html.ValidationMessageFor(m => m.Genre)</td> 
     </tr> 
     <tr> 
      <td> 
       <label>Price:</label></td> 
      <td>@Html.EditorFor(m => m.Price)</td> 
      <td>@Html.ValidationMessageFor(m => m.Price)</td> 
     </tr> 
    </table> 
    <button type="submit">Submit</button> 
} 

과의

이제는 다음과 같은 문제가 있습니다. 가격 만 입력하면 modelstate.isvalid가 true가됩니다. 내 모델 위에 마우스를 올리면 이름과 장르가 모두 null입니다. 물론 필요하지만 유효성 검사는 작동하지 않습니다. 또한 유효성 확인 메시지는 가격에서만 작동합니다.

나는 너무 우스꽝스러운 것을 간과하지 않기를 바랍니다. 도와 주셔서 감사합니다!

+0

제출을 클릭하면 어떤 일이 발생을 허용하지되어 있는지 확인 ? –

+0

가격을 입력하면 modelstate가 유효 해지고 인덱스로 이동합니다. 가격을 기입하지 않으면 View()를 반환합니다. 가격 만 오류를줍니다. 이름과 장르 절대 오류를 주거나 유효하지 않은 상태로 만듭니다. – whodares

답변

13

반환 잘못된 다시보기로 모델 :

[HttpPost] 
public ActionResult Add(MovieModel model) 
{ 
    if(ModelState.IsValid) 
    { 
     return RedirectToAction("Index"); 
    } 
    return View(model); // <---- 
} 

아, 그리고 필수 속성은 빈 문자열

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.allowemptystrings.aspx

public class MovieModel 
{ 
    public int Id { get; set; } 

    [Required(AllowEmptyStrings = false)] 
    public string Name { get; set; } 

    public DateTime ReleaseDate { get; set; } 

    [Required(AllowEmptyStrings = false)] 
    public string Genre { get; set; } 

    [Required] 
    public decimal Price { get; set; } 

    public virtual ICollection<RoleInMovie> RoleInMovie { get; set; } 
} 
+0

답변 해 주셔서 감사합니다. 그러나 이것은 작동하지 않았습니다. 항상 가격 만 확인됩니다. – whodares

+0

@ThomasSchellekens 내 업데이트보기 – asawyer

+0

기호를 해결할 수 없습니다. AllowEmptyStrings는 현재 받고있는 오류입니다. 내 Resharper가 나를 놓친 참조를 가리키고 있지 않거나 뭔가를 내려다보고 있습니까? – whodares

관련 문제