Implement specific field validation

Dec 30, 2009 at 5:07 PM

I would like to implement specific validation rules at the controler levels. The current validation is included in the GenericCrudController class.

What would be the suggested procedure in order to override it?

 

Thanks,

Claude

 

 

Dec 30, 2009 at 9:59 PM

I found some good tutorials on the ASP MVC we site.  http://www.asp.net/learn/mvc/#MVC_Validation

Works great right from the productController.

I just override the Edit class. Happy not to have to modify the GenericCrudController class.

 

[AcceptVerbs(HttpVerbs.Post)]
        public override ActionResult Edit(RetiredProduct item)
        {
            // Validation logic
            if (item.PartNumber.Trim().Length == 0)
                ModelState.AddModelError("partNumber", "Part Number is required.");
            if (item.Name.Trim().Length == 0)
                ModelState.AddModelError("Name", "Name is required.");
            if (item.en_prod_multi == "--Choose One--")
                ModelState.AddModelError("en_prod_multi", "Please choose a card category");
            if (!ModelState.IsValid)
                return View(item);
            // Database logic
            try
            {
                SaveItem(item);
                ViewData["Success"] = "<ul class='success'><li>Edited successfully</li></ul>";
                return View(item);
            }
            catch
            {
                return View();
            }
        }

[AcceptVerbs(HttpVerbs.Post)]

        public override ActionResult Edit(Product item)

        {

        }

 

 

 

Coordinator
Jan 3, 2010 at 1:51 PM

Your best bet (if i follow what you mean) is to use a model binder.  You can either use the normal mvc model binder else MVCCrud has a more automated one.  

By default it will automatically map to an “id” column (the column name can be changed in the constructor if you want).  From there all you do is override the ExtraBindings method and say what other columns to map, what error message to show and wether the column can be null / blank.  You could also do other checks in here eg dates fall within a range.  Add any errors to the ModelState.  This is where you could do the custom validation eg model.Name != "Matthew" and add the error to the controller context model state like you would if you were using the normal mvc model binder.

public class PersonModelBinder : AutomatedModelBinder<Person>

    {

        public override void ExtraBindings()

        {

            parseFromForm("name", "No name", true); //cannot be blank

        }

    }

And register this in the global.asax

ModelBinders.Binders[typeof(tblProduct)] = new ProductModelBinder();