2012-09-10 92 views
2

我正在ASP.NET MVC 4中工作,而且我的问题是我的模型验证工作不正确。出于某种原因,不是所有我需要的领域都在填写mvc模型验证不需要在所有字段上工作

这里是我的模型:

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

这是我的行动:

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

现在是这样的事情:只要我输入一个价格,modelstate.isvalid就会成为现实。当悬停在我的模型上时,名称和流派都为空。当然他们是必需的,但验证不起作用。 另外,validationmessagefor只适用于价格。

我希望我不会忽略太荒谬的东西。谢谢您的帮助!

+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