More Html.ValidateTextBox
Posted on September 15, 2008OK. So I added some server side rule checking as a backup to the client side stuff. In order to test this out, I had to turn off client side validation. Right now it only returns a list of validation error messages, but I have some plans for that mechanism. The controller method that handles the form post now looks like this:
[AcceptVerbs("POST")]
public ActionResult Edit(int id, Customer customer)
{
customer.ID = id;
if (!Model.IsValid(customer))
{
ViewData["errormessages"] = Model.GetErrorMessages(customer);
return View(customer);
}
RepoFactory.Get<Customer>().Save(customer);
return this.RedirectToAction("index");
}
| |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
The only change i made to the Customer class so far was that I added a custom model binder attribute to the customer. That attribute looks like this:
public class CustomerBinder : IModelBinder
{
public object GetValue(ControllerContext controllerContext,
string modelName,
Type modelType,
ModelStateDictionary modelState)
{
NameValueCollection form = controllerContext.HttpContext.Request.Form;
return new Customer
{
FirstName = form["FirstName"],
LastName = form["LastName"]
};
}
}
| |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
And the customer class looks like this(i updated the validation attribute constructors to match the changes i made.
[ModelBinder(typeof(CustomerBinder))]
public class Customer : IModel
{
public int ID { get; set; }
[ValidateLength(3, 30,
"First name must be between 3 and 30 characters in length.", true)]
public string FirstName { get; set; }
[ValidateMaxLength(30,
"Last name is required and cannot exceed 30 characters.", true)]
public string LastName { get; set; }
}
| |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
and the server side validation ends up rendering the following view(reminiscent of lammo validation summary in webforms):