我正在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只适用于价格。
我希望我不会忽略太荒谬的东西。谢谢您的帮助!
会发生什么,当你点击提交? –
如果我填入一个价格,modelstate变得有效,我去索引。如果我没有填写价格,我会返回View();只有价格会给出错误。名称和流派不要给错误或使模型状态无效。 – whodares