asp.net MVC 3验证了Id字段与EF code第一 [英] asp.net mvc 3 validation for Id field with EF code first

查看:181
本文介绍了asp.net MVC 3验证了Id字段与EF code第一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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

和下面的一对添加方法控制器:

and the following pair of Add methods in the controller:

[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字段是必需的。

Everything is displayed just fine, unfortunately I am unable to submit the form. It took me a while to figure out that the Id field gets validated. Indeed, if I remove the HiddenInput attribute, I can see on submitting that it tells me the Id field is required.

有没有一种方法,同时仍使用其标记为不要求 EditorForModel()

Is there a way to mark it as not required while still using EditorForModel()?

推荐答案

如果你必须保持主键作为模型的一部分​​,那么你需要覆盖 DataAnnotationsModelValidatorProvider 值类型是必需的。以下内容添加到Application_Start方法中的的Global.asax.cs

If you must keep the primary key as part of the model, then you need to override the default for DataAnnotationsModelValidatorProvider that value types are required. Add the following to the Application_Start method in Global.asax.cs:

ModelValidatorProviders.Providers.Clear(); 
ModelValidatorProviders.Providers.Add(new DataAnnotationsModelValidatorProvider());
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

这篇关于asp.net MVC 3验证了Id字段与EF code第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆