How to validate that a dropdown list item has been

2019-07-17 10:33发布

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.

2条回答
看我几分像从前
2楼-- · 2019-07-17 10:56

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...)

查看更多
戒情不戒烟
3楼-- · 2019-07-17 11:03
ModelState.AddModelError("ddlDistrict", "Please select a district");
ModelState.SetModelValue("ddlDistrict", ValueProvider["ddlDistrict"]);
查看更多
登录 后发表回答