asp.net mvc 3验证Id字段,首先是EF代码

本文关键字:EF 代码 字段 mvc net 验证 Id asp | 更新日期: 2023-09-27 18:07:36

我有以下模型:

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");
}

这是Add视图:

@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() ?

asp.net mvc 3验证Id字段,首先是EF代码

如果您必须保留主键作为模型的一部分,那么您需要覆盖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之类的工具将视图模型映射回您的域模型

[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");
}