Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - asp.net mvc 3 validation for Id field with EF code first

I have the following model:

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

This is the Add view:

@using Models
@model Product

<h2>Add Product</h2>

@using (@Html.BeginForm("Add", "Home")) {
  @Html.AntiForgeryToken()
  @Html.EditorForModel()
  <input type="submit" id="btnSubmit" value="Submit"/>
}

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...