set select value in IEnumerable<SelectListItem> c# mvc [duplicate]

我的未来我决定 提交于 2019-12-02 11:50:16

The Selected property of SelectListItem is ignored when binding to a model property. You need to set the value of your Status property in the GET method before you pass the model to the view

List<SelectListItem> Discountdata = new List<SelectListItem>
{
    new SelectListItem() { Value = "All", Text = "All" },
    new SelectListItem() { Value = "Draft", Text = "Draft" },
    new SelectListItem() { Value = "Issued", Text = "Issued" },
    ....

};
StatusClass model = new CRM.StatusClass
{
    StatusList = Discountdata,
    Status = "Issued"
};
return View(model);

and the 2nd option in your <select> element will be selected.

Note that Discountdata is already IEnumerable<SelectListItem> and using new SelectList(Discountdata, "Value", "Text") to create an identical IEnumerable<SelectListItem> is unnecessary extra overhead.

Note also that since you have the same value for both the value attribute and display text, you could simply use

List<string> Discountdata = new List<string>{ "All", "Draft", "Issued", ... };

and in the model constructor

StatusList = new SelectList(Discountdata),

You're binding Status property to the dropdown. So set the value either from database, or in your case, a default value "Issued" like this:

statusObj.Status = "Issued"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!