who does the validation in basic asp.net mvc + entity framework program
I have a very simple ASP.NET MVC application with Entity Framework-based model. Essentially, just a Product table from AdventureWorks database. Controller only has Index and CrUD methods.
Create has the following:
if (!ModelState.IsValid) {
return View();
}
// Save to the database
Some of the fields are required in the database, and if the values are not entered, I get an error (ModelState.IsValid == false). However, I want to supply some default values instead of erroring out. But i can't figure out how to hook into model validation... I played with "buddy metadata" class; so I know how to change error messages through annotations; but not how to "buddy" the validation process.
If it makes it clearer, I would like to set ModifiedDate to DateTime.Now, and rowguid to Guid.NewGuid(). Needless to say, the real problem is in a large application, but this example seems like a perfect summary of what I am trying to solve.
I probably do it in the controller by navigating through ModelState, but there gotta be a better way.
It may be a very simple question... but I couldn't find any examples how to do开发者_JAVA百科 that.
What you propably need is to exlude some fields from binding. Sample code:
[HttpPost]
public ActionResult Create([Bind(Exclude = "rowGuid,ModifiedDate")]Task task)
{
if (ModelState.IsValid)
If it is exluded from binding, it is excluded from validation. You'll be able to set it yourself without having model errors.
精彩评论