1

In this code in an Edit view, the correct vendor name text appears but it is not validated when I blank its textbox and push Save. The Vendor is a property of the Order model, and VendorName is a property in the Vendor model. They relate referentially. My form does not all input into a single table, but on satellite tables as well.

<%= Html.TextBox("Vendor.VendorName")%> <%= Html.ValidationMessage("Vendor.VendorName")%> 

Why is validation not occuring?

This seems to work, but it seems like a hack to me:

using M = HelloUranus.Models //... namespace HelloUranus.Controllers { public class OrderDetailController : Controller { //... private M.DBProxy db = new M.DBProxy(); [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection collection) { //... var orderDetail = db.GetOrderDetail(id); //... try { if (string.IsNullOrEmpty(Request.Form["Vendor.VendorName"])) { throw new Exception(); } UpdateModel(orderDetail); db.Save(); return RedirectToAction("Details", new {id = orderDetail.odID } ); } catch { ModelState.AddRuleViolations(orderDetail.GetRuleViolations()); return View(orderDetail); } //... } //... } 
0

    1 Answer 1

    2

    Did you write any validation code? You have to manually validate it in your controller. If you:

    ModelState.IsValid = false; 

    in the controller, for example, you will see some validation. That will trigger the ValidationSummary on the View to be shown. To actually add a validation to a single form element, use:

    ModelState.AddModelError("Vendor.VendorName", string.Format("Vendor name must be at least {0} characters.",10)); 

    Note that this will also set the ModelState to an invalid state and thus trigger the ValidationSummary as well.

    4
    • 1
      ModelState.AddModelError automatically sets IsValid to false.CommentedAug 20, 2009 at 20:10
    • You're right, my mistake. I knew you had to remember something, but that something is setting the ModelStateDictionary up to repopulate your form with the invalid data using SetModelValue. Lemme edit that out.CommentedAug 20, 2009 at 20:14
    • Where in the workflow would I execute ModelState.AddModelError("Vendor.VendorName", "*") ? If done in the try section of the Save portion of the edit-post action method, it throws an exception since ModelState.IsValid becomes false.CommentedAug 20, 2009 at 20:21
    • Post your code and I can help you sort it out. Alternatively, take a look at how its done in the AccountController that is included by default in a new project.CommentedAug 20, 2009 at 21:00

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.