繁体   English   中英

如果未选择任何值,则Html.DropDownListFor会给出错误

[英]Html.DropDownListFor gives error if no value selected

我有一个@Html.DropDownListFor ,它显示数据库中的项目列表。

非常简化,我有一个带有这些参数的ViewModel

public class RegisterViewModel
{
    [Required]
    [Display(Name = "Country")]
    public string SelectedCountryId { get; set; }
    public IEnumerable<System.Web.Mvc.SelectListItem> CountryList { get; set; }

    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }
}

然后,我在控制器中使用以下命令填充IEnumerable<System.Web.Mvc.SelectListItem>

    IEnumerable<SelectListItem> countries = _DB.Countries.Where(x => x.Status == Status.Visible)
                        .Select(x => new SelectListItem()
                        {
                            Value = x.ID + "",
                            Text = "(+" +x.PhoneCountryCode + ") - " + x.Name
                        }).ToList();
    countries.First().Selected = true;

然后,我使用以下HTML来显示选项集

@Html.DropDownListFor(m => m.SelectedCountryId, Model.CountryList, new { @class = "form-control" })

在页面加载时,选项列表始终具有第一个选项,如果单击它,则可以选择三个选项。

我的问题是,如果您不打开列表并选择一个项目(即,将其保留为默认值),则会从我的视图中抛出此错误,

键为“ SelectedCountryId”的ViewData项的类型为“ System.String”,但必须为“ IEnumerable”类型。

如果您打开下拉列表并手动选择一个项目,则不会发生此错误。 如果我从列表中SelectedCountryId其他项目,则SelectedCountryId确实会获得正确的值。

我尝试关闭public string SelectedCountryId { get; set; } public string SelectedCountryId { get; set; } public string SelectedCountryId { get; set; }string改为IEnumerable<SelectListItem> ,这确实使错误消失了,但是列表始终为空。

有什么好主意吗?

在您的控制器中当模型无效时,重新填充下拉列表:

if (ModelState.IsValid)
{
IEnumerable<SelectListItem> countries = _DB.Countries.Where(x => x.Status == Status.Visible)
                    .Select(x => new SelectListItem()
                    {
                        Value = x.ID + "",
                        Text = "(+" +x.PhoneCountryCode + ") - " + x.Name
                    }).ToList();
countries.First().Selected = true;
}
else
{
  //We need to rebuild the dropdown or we're in trouble
   IEnumerable<SelectListItem> countries = _DB.Countries.Where(x => x.Status == Status.Visible)
                        .Select(x => new SelectListItem()
                        {
                            Value = x.ID + "",
                            Text = "(+" +x.PhoneCountryCode + ") - " + x.Name
                        }).ToList();
    countries.First().Selected = true;
}

您还可以使用此方法检查模型状态中的错误。 可能是一些有趣的东西:

var errors = ModelState
                .Where(x => x.Value.Errors.Count > 0)
                .Select(x => new { x.Key, x.Value.Errors })
                .ToArray();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM