MVC下拉列表总是显示Model.Invalid?

时间:2013-12-13 21:28:45

标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5

表单发布后的

`Model.InValid'。错误来自下拉列表。

模型

    [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>

控制器

[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

怎么过来这个?帖子list<courties> Countries中的内容为空。

1 个答案:

答案 0 :(得分:3)

您在列表中需要而不是所选值。应该是

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

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