我有以下型号:
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()
时将其标记为不需要?
答案 0 :(得分:7)
如果必须将主键作为模型的一部分,则需要覆盖DataAnnotationsModelValidatorProvider
的默认值,即需要值类型。将以下内容添加到Global.asax.cs
中的Application_Start方法:
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new DataAnnotationsModelValidatorProvider());
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
答案 1 :(得分:1)
您应该考虑使用视图模型,而不是将域实体作为模型发送到视图。
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");
}