views:

63

answers:

1

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 that.

A: 

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.

LukLed
alas, this was one of the first things I tried... Whether I create an Exclude list or not, ModelState still comes with IsValid == false and all entries (including rowGuid and ModifiedDate) are part of error dictionary
Felix