asp.net-mvc ASP.NET MVC(razor)列表框多选值到字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8729144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC (razor) Listbox multiselect values to string
提问by Matt Millican
I have two multi-select list boxes; one with months and one with years such as the following:
我有两个多选列表框;一个是月份,一个是年份,如下所示:
@Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeMonths, Model.TimeframeMonths)
@Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeYears, Model.TimeframeYears)
I'm saving the both values to the database as a comma separated list (string/nvarchar). The values are being like this: Months:1,3,7; Years:2002,2005
我将这两个值作为逗号分隔列表(字符串/nvarchar)保存到数据库中。值是这样的:月数:1,3,7;年份:2002、2005
For some reason when I pull the values back out to the form, the months are pre-selecting in the listbox fine, but the years are not.
出于某种原因,当我将值拉回表单时,列表框中的月份可以很好地预先选择,但年份不是。
Any ideas?
有任何想法吗?
EDIT- Additional code samples:
编辑- 其他代码示例:
Controller - Manage
控制器 - 管理
public ActionResult Manage(Guid id)
{
var list = _listService.GetList(id);
var model = LoadModelFromObject(list);
model.TimeframeMonths = GenerateMonthDropdown();
model.TimeframeYears = GenerateYearDropdown(model.IncludeGuestsArrivedInTimeframeYears.Split(','));
model.DaysOfWeek = GenerateDaysOfWeekDropdown();
return View(model);
}
Controller - 'Helper'
控制器 - '助手'
private IList<SelectListItem> GenerateYearDropdown(string[] selected)
{
var list = new List<SelectListItem>();
var startYear = DateTime.Now.Year - 10;
for (int idx = startYear; idx < startYear + 11; idx++)
{
list.Add(new SelectListItem
{
Value = idx.ToString(),
Text = idx.ToString(),
Selected = selected != null && selected.Contains(idx.ToString())
});
}
return list;
}
View
看法
@Html.CheckBoxFor(m => m.IncludeGuestsArrivedInTimeframe)
@Html.LabelFor(m => m.IncludeGuestsArrivedInTimeframe)
@Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeMonths, Model.TimeframeMonths)
@*@Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeYears, Model.TimeframeYears)*@
@Html.ListBox("IncludeGuestsArrivedInTimeframeYears", Model.TimeframeYears)
回答by tugberk
You need to set Selectedproperty of SelectItemListclass to true for the options which you want to be pre-selected.
对于要预先选择的选项,您需要将 class 的Selected属性设置SelectItemList为 true。
Example:
例子:
@{
var foo = new List<SelectListItem> {
new SelectListItem { Text = "Foo 1", Value = "1", Selected = true },
new SelectListItem { Text = "Foo 2", Value = "2" },
new SelectListItem { Text = "Foo 3", Value = "3", Selected = true }
};
}
@Html.ListBox("foo", foo)
In this case, Foo 1 and Foo 3 should appear as pre-selected. The above code generates the below html markup:
在这种情况下,Foo 1 和 Foo 3 应显示为预选。上面的代码生成下面的 html 标记:
<select id="foo" multiple="multiple" name="foo">
<option selected="selected" value="1">Foo 1</option>
<option value="2">Foo 2</option>
<option selected="selected" value="3">Foo 3</option>
</select>
Edit:
编辑:
First of all, replace this code:
首先,替换这段代码:
list.Add(new SelectListItem {
Value = idx.ToString(),
Text = idx.ToString(),
Selected = selected != null && selected.Contains(idx.ToString())
});
with this code:
使用此代码:
list.Add(new SelectListItem {
Value = idx.ToString(),
Text = idx.ToString(),
Selected = true
});
Then run the app. If all the options are pre-selected, then I bet that this selected != null && selected.Contains(idx.ToString())does not satisfy the condition.
然后运行应用程序。如果所有选项都是预先选择的,那么我敢打赌这selected != null && selected.Contains(idx.ToString())不满足条件。
回答by Navpreet Singh
Another way of doing it
另一种方法
@Html.ListBox("categoryId", new MultiSelectList(ViewData["categories"] as System.Collections.IEnumerable, "Id", "CategoryName", Model.tIdx_ProductCategories.Select(x => x.CategoryId).AsEnumerable()))
Explanation:
解释:
categoryId- would be name of control, when rendered as htmlViewData["categories"]- is list of categories withIdandCategoryNamepropertiesModel.tIdx_ProductCategoriescarries the list of category ids to be selected in list box.
categoryId- 将是控件的名称,当呈现为 html 时ViewData["categories"]- 是具有Id和CategoryName属性的类别列表Model.tIdx_ProductCategories携带要在列表框中选择的类别 id 列表。
回答by Alex Mazzariol
As it seems (e.g. here Preselect Items in Multiselect-Listbox (MVC3 Razor)) the Razor engine happily ignoresthe Selected property and compares the list from the model and the supplied option list by calling ToString() on the objects from the model and using string comparison to select.
看起来(例如,这里是多选列表框(MVC3 Razor)中的预选项目),Razor 引擎愉快地忽略了 Selected 属性,并通过对模型中的对象调用 ToString() 并使用来比较模型中的列表和提供的选项列表要选择的字符串比较。
What I cannot explain to myself is whythis behavior is used with Html.ListBox(), which does not use any model and expects a collection of SelectListItem.
我无法向自己解释的是为什么这种行为与 Html.ListBox() 一起使用,它不使用任何模型并需要 SelectListItem 的集合。
Think it's a bug, but it does not seem to have been addressed recently.
认为这是一个错误,但最近似乎没有得到解决。

