DropDownListFor不显示当前值MVC

时间:2015-03-19 14:35:15

标签: c# asp.net-mvc html.dropdownlistfor

我有一个下拉列表,但我无法在视图中显示当前状态:

我的HTML:

<div class="form-group">
    @Html.LabelFor(model => parts.Status, new { @class = "col-md-4" })

     //This shows the status as "New - Dispatch"
    @Html.TextBoxFor(model => parts.Status, new { @class = "col-md-8 required-color" })

     //This shows as empty , but i want it to show as New - Dispatch
    @Html.DropDownListFor(model => parts.Status, parts.StatusList, String.Empty, new { @class = "col-md-8 required-color" })
</div>

我从这里获取数据:

StatusList = _partsRequestHServices.GetStatusList(parts.PartRequestStatus)

这是我的清单:

public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
    List<SelectListItem> list = new System.Collections.Generic.List<SelectListItem>();
    list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch"});
    list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse"});
    list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim" });

    return list;
}

我希望在TextBoxFor中的视图中显示当前状态,但不在DropDownListFor中显示。

2 个答案:

答案 0 :(得分:0)

您需要返回SelectList而不是通用List<SelectListItem>()。通过返回此类列表,您可以设置所选项的值。像这样:

public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
    list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch", Selected = false });
    list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse", Selected = false });
    list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim", Selected = false });   
}

然后像这样消费:

var statuses = GetStatusList("??");
SelectList statusList = new SelectList(statuses , "Id", "Text", selectedValue);
ViewData["Statuses"] = statusList;

如果您在下拉列表中使用自定义模板进行此设置,请确保Status的视图模型属性具有以下属性:

[UIHint("string-name-of-editor-template")]

答案 1 :(得分:0)

Selected = false移除SelectListItem(使用Selected = false,您明确表示您不希望其中任何一个被选中):

public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
    List<SelectListItem> list = new System.Collections.Generic.List<SelectListItem>();
    list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch" });
    list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse" });
    list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim" });

    return list;
}