James123
James123

Reputation: 11652

MVC dropdownlist always shows Model.Invalid?

`Model.InValid' after form post in. Errors are coming from dropdown list.

Model

    [Required]
    [Display(Name = "Country")]
    public List<Countries> Countries { get; set; }

    public string CountryCode { get; set; }

Index.cshtml

<div class="form-group">
  <div class="col-sm-5">
        @Html.LabelFor(model => model.Countries, new { @class = "control-label" })
        <span class="red">*</span>

        </div>
        <div class="col-sm-7">
           @Html.DropDownList("CountryCode", new SelectList(Model.Countries,
           "CountryCode", "CountryDesc"), new { @class = "btn btn-default 
            dropdown-toggle" })

           @Html.ValidationMessageFor(model => model.Countries, "", 
           new { @style = "color:Red" })
        </div>
  </div>

Controller

[HttpPost]
public JsonResult Index(Contact contact)
{
   if (ModelState.IsValid) // Alway is false, because countries prop is null
   {
       //code here
      var result = new { Success = "True", Message = "No Error" };
      return Json(result, JsonRequestBehavior.DenyGet);                           
   }
   else
   {
      var result = new { Success = "False", Message = "Invalid state" };
      return Json(result, JsonRequestBehavior.DenyGet);
   }
}

enter image description here

How to over come this? in the post list<courties> Countries is coming as null.

Upvotes: 0

Views: 485

Answers (1)

Matt Bodily
Matt Bodily

Reputation: 6423

you have required on the list and not the selected value. should be

[Display(Name = "Country")]
public List<Countries> Countries { get; set; }

[Required]
public string CountryCode { get; set; }

Upvotes: 3

Related Questions