views:

51

answers:

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);
        }
        //...
      }
      //...
    }
+2  A: 

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.

JoshJordan
ModelState.AddModelError automatically sets IsValid to false.
Russell Steen
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.
JoshJordan
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.
JonathanWolfson
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.
JoshJordan