ModelState对空白Html.DropDownList无效

时间:2014-03-06 21:04:38

标签: c# entity-framework asp.net-mvc-4

我有一个带有下拉列表的表单,其中包含空白选项。我希望用户能够根据需要输入空白选项。但是,模型状态返回对CountryID无效。任何帮助将不胜感激。

Create.cshtml:

@(Html.DropDownList("CountryID", Model.Countries, ""))

Office.cs:

public class Office
{
    public Office()
    {
    }

    public Office(Int32 SyncID, string OfficeName)
    {
        this.SyncID = SyncID;
        this.OfficeName = OfficeName;
    }

    public Int32 OfficeID { get; set; }
    public Int32 SyncID { get; set; }
    public Int32 OfficeRollupID { get; set; }
    public Int32 StateProvID { get; set; }
    public Int32 CountryID { get; set; }
    public bool Active { get; set; }

    [Required]
    [Display(Name="Office Name")]
    public string OfficeName { get; set; }

    [Display(Name = "Office Rollup")]
    public IEnumerable<SelectListItem> OfficeRollups { get; set; }

    [Display(Name = "State/Province")]
    public IEnumerable<SelectListItem> StateProvinces { get; set; }

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

    public List<SquareFootage> SquareFootages { get; set; }
}

HomeController.cs:

[HttpPost]
public ActionResult Create(Office model)
{
    if (ModelState.IsValid)
    {
        //db.SaveChanges();

    }

    return View(model);
}

1 个答案:

答案 0 :(得分:1)

使countryId可以为空

public int? CountryID { get; set; }