验证mvc4中的下拉列表?

时间:2013-02-21 09:27:52

标签: asp.net-mvc razor asp.net-mvc-4

我想确保用户在提交表单之前从下拉列表中选择一个值。请看下面的代码。我究竟做错了什么 ?感谢

查看

  @model Store.Models.StoreDTO
      List<Store.Models.CountryDTO> countriesList= ViewBag.Countries;
            var countryItems = new SelectList(countriesList, "CId", "CName");

    @Html.DropDownListFor(x => x.Countries.SingleOrDefault().CId, @countryItems )
                     @Html.ValidationMessageFor(x=>x.Countries.SingleOrDefault().CId) 

    <input class="btn btn-info" type="submit" value="Search" />

查看-模型

public class StoreDTO
{
public IEnumerable<CountryDTO> Countries { get; set;}
}

public class CountryDTO
{
    [DisplayName("CId")]
    [UIHint("DropDownList")]
    [Required(ErrorMessage = "Please select a Country")]
    public string CId { get; set; }
    [Required]
    public string CName { get; set; }
}

1 个答案:

答案 0 :(得分:1)

帮助程序不支持以下lambda表达式:

x => x.Countries.SingleOrDefault().CId

仅支持简单的属性访问表达式。

正确的方法是在视图模型上定义一个Cid属性,该属性将从下拉列表中保存所选的国家/地区ID:

public class MyViewModel
{
    [DisplayName("CId")]
    [Required(ErrorMessage = "Please select a Country")]
    public string CId { get; set; }

    ...
}

然后在视图中将下拉列表绑定到此标量属性:

@Html.DropDownListFor(
    x => x.CId, 
    new SelectList((IEnumerable<Store.Models.CountryDTO>)ViewBag.Countries, "CId", "CName"),
    "-- SELECT --"
)
@Html.ValidationMessageFor(x => x.CId)