从使用的SelectList默认值创建DropDownListFor [英] Create DropDownListFor from SelectList with default value

查看:400
本文介绍了从使用的SelectList默认值创建DropDownListFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dropdownlistfor

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
 @Html.ValidationMessageFor(model => model.Item.Item.Status)

HTML输出:

<select id="statusDropdown" class="valid" name="Item.Item.Status" data-val-required="The Status field is required." data-val-number="The field Status must be a number." data-val="true">
<option value="2">Completed by Admin</option>
<option value="3">General Error</option>
<option value="4">New</option>
</select>



我怎样才能更新这个代码来设置选择的选项默认? EG

How can I update this code to set a default selected option? E.G.

<期权价值=4选中>全新< /选项>

我想:

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description",@Model.SelectedStatusIndex), new { id = "statusDropdown" })

@ Model.SelectedStatusIndex 有4个值,但不改变默认选项。新

@Model.SelectedStatusIndex has a value of 4, but does not change the default option to New.

我也试过:

@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
@Html.ValidationMessageFor(model => model.Item.Item.Status)

这选择默认选项新建 ,但 model.Item.Item.Status 将不包含在HTTP POST的下拉菜单设置。

This selects the default option "New", but model.Item.Item.Status is not set by the dropdown on HTTP POST.

其他细节:

model.Item.Item.Status 是一个int。 @ Model.AllStatus 是一个SQL表,列出了所有可用的状态选项。

model.Item.Item.Status is an int. @Model.AllStatus is a SQL table that lists all available status options.

推荐答案

有已经存在关于这里 。其中一个问题可能会使用不同的类型字符串的键值。我曾在过去类似的问题,我知道,我解决它像 - 明确设置选定 准备列表时,属性(在你的情况, AlLStatus )。

There exist already some discussions about that here or there. One of the problems might be using a different type than string for the key value. I had similar problems in past and I know that i solved it like this - explicitly setting the Selected property when preparing the list (in your case, AlLStatus).

将意味着,为您的情况下(控制器的动作):

Would mean, for your case (in controller action):

IEnumerable<SelectListItem> selectList = 
from s in allStatus // where ever you get this from, database etc.
select new SelectListItem
{
    Selected = (s.id == model.Item.Item.Status),
    Text = cs.Description,
    Value = s.id.ToString()
};
model.AllStatus = selectList;

这篇关于从使用的SelectList默认值创建DropDownListFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆