[英]asp.net mvc 3 validation for Id field with EF code first
我有以下型号:
public class Product
{
[Key]
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required]
[StringLength(10)]
public string ProductCode { get; set; }
[Required]
[StringLength(40)]
public string ProductName { get; set; }
}
以及控制器中的以下一对Add方法:
[HttpGet]
public ActionResult Add()
{
return View();
}
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Add(Product product)
{
productRepository.Add(product);
return RedirectToAction("Index");
}
这是添加视图:
@using Models
@model Product
<h2>Add Product</h2>
@using (@Html.BeginForm("Add", "Home")) {
@Html.AntiForgeryToken()
@Html.EditorForModel()
<input type="submit" id="btnSubmit" value="Submit"/>
}
一切都显示得很好,不幸的是我无法提交表格。 我花了一段时间才弄清楚Id字段是否经过验证。 实际上,如果我删除了HiddenInput
属性,我可以看到提交时它告诉我需要Id字段。
有没有办法在仍然使用EditorForModel()
时将其标记为不需要?
如果必须将主键作为模型的一部分,则需要覆盖DataAnnotationsModelValidatorProvider
的默认值,即需要值类型。 将以下内容添加到Global.asax.cs
的Application_Start方法:
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new DataAnnotationsModelValidatorProvider());
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
您应该考虑使用视图模型,而不是将域实体作为模型发送到视图。
public class ProductAddModel
{
[Required]
[StringLength(10)]
public string ProductCode { get; set; }
[Required]
[StringLength(40)]
public string ProductName { get; set; }
}
然后使用AutoMapper之类的工具将viewmodel映射回您的域模型
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Add(ProductAddModel productAddModel)
{
if (ModelState.IsValid)
{
Product product = Mapper.Map<ProductAddModel, Product>(productAddModel);
productRepository.Add(product);
}
return RedirectToAction("Index");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.