tags:

views:

221

answers:

3

Well, this must be easy, but ...

I have a dropdown list in my view:

<%= Html.DropDownList("ddlDistricts", 
Model.clients.DistrictList,"-- select district --", 
new { @class = "ddltext", style="width: 200px", onchange = "this.form.submit();" }) %>

Model.clients.DistrictList is of type SelectList.

What I want to do is make sure the user selects something (i.e., "--- select district-- ", which has a value of "", is not selected).

So in the controller I have:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(string date, string month, FormCollection form)
    {

         if (form["chooseSchool"] == "Submit")  // submit button is clicked
        {
                if (String.IsNullOrEmpty(form["ddlDistrict"]))
                {
                    ModelState.AddModelError("ddlDistrict", "Please select a district");
                }
                else
                {
                    // store some data somewhere .......

                }

        }

         // create the modelData object .....

         return View(modelData);

     }

But what happens is there is a null object exception when it attempts to redisplay the view, apparently because

ModelState["ddlDistricts"].Value is null, so it can't apply ModelState["ddlDistricts"].Value.AttemptedValue as the value of the dropdown list.

According to what I have read, in attempting to supply a value to a field when ModelState.IsValid is false, it attempts to provide a value for the control with the error in this order:

(1) ModelState["fieldname"].Value.AttemptedValue

(2) Explicitly provided value in control

(3) ViewData

So it is applying ModelState, but the Value property is null, so trying to access AttemptedValue generates an exception.

What is the answer to this? How can you check to make sure a legitimate item has been selected from a DropDownList?

I'm sure it's easy, but I can't seem to do it using the ModelState error-handling scheme.

A: 
ModelState.AddModelError("ddlDistrict", "Please select a district");
ModelState.SetModelValue("ddlDistrict", ValueProvider["ddlDistrict"]);
Darin Dimitrov
Ah ha! That looks hopeful .. I will have to wait until Friday when I get back to work to try it. I have seen SetModelValue here and there, but have not found a really good explanation of it.
Cynthia
A: 

You have a drop down named "ddlDistricts" (plural) in view but reference "ddlDistrict" in your code. (Unless it is a typo in your question text only...)

PanJanek
Oh yeah, it's just a typo .. the code is correct. :)
Cynthia
A: 

This did it:

ModelState.SetModelValue("ddlDistricts", ValueProvider["ddlDistricts"]);

Thanks Darin!

(I don't know how to set your post as the correct one; it doesn't seem to recognize me as the author and doesn't provide that option. But thanks anyway!)

Cynthia