拉的SelectList信息来源ViewBag:不创造价值=" ..."在生成html [英] SelectList pulling info from ViewBag: not creating value="..." in generated html
问题描述
我想使用的Razor视图引擎打造在MVC4应用程序客户端验证的下拉列表。
I'm trying to create a client-side validated dropdown list in an MVC4 application using the Razor view engine.
在code在视图中产生下拉列表如下:
The code in the view to generate the dropdown list is as follows:
@Html.DropDownList("Test", new SelectList(ViewBag.AvailableLoBsDescriptions, ViewBag.AvailableLoBsIds), "--none--")
注意ViewBag.AvailableLoBsDescriptions在使用一个IList控制器中创建的,同时也是在控制器使用一个IList创建ViewBag.AvailableLoBsIds。
Note that ViewBag.AvailableLoBsDescriptions is created in the controller using an IList while ViewBag.AvailableLoBsIds is also created in the controller using an IList.
我希望发生的是有剃刀生成一个下拉菜单,说明填充每个内部HTML,而IDS填充值=...。然而,对价值产生什么都没有,结果是这样的:
What I expected to happen is have Razor generate a dropdown menu where Descriptions populates the inner html of each while the Ids populates the value="...". However, there is nothing generated for value at all, resulting in something like this:
<select id="Test" name="Test"><option value="">--none--</option>
<option>N/A</option>
<option>aaaa</option>
<option>bbbb</option>
<option>cccc</option>
<option>dddd</option>
<option>eeee</option>
<option>ffff</option>
</select>
综观选择列表的文档的http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx,在我看来,这应该工作。有没有人有一个想法,为什么没有被除占位符以外的任何生成的值?
Looking at the SelectList documentation, http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx, it seems to me that this should work. Does anyone have an idea why the values are not being generated for anything other than the placeholder?
谢谢!
推荐答案
构造您所使用如下所示:
The constructor you are using looks like the following:
SelectList(IEnumerable, Object)
第二个参数在这里决定了的当前选择的从集合中的第一个参数对象。它并不规定一个对象作为值的列表来使用。
The second parameter here dictates the currently selected object from the collection in the first parameter. It does not dictate an object to use as a list of values.
你应该使用的SelectList(IEnumerable的,字符串,字符串)做
。这使您可以通过用于描述和一个值(的IEnumerable
的每个元素的)属性的名称。然后,您可以产生这样的:
What you should be doing is using SelectList(IEnumerable, String, String)
. This allows you to pass the name of a property (of each element of IEnumerable
) to use for the description and one for the value. You can then produce something like this:
控制器:
// Create your IEnumerable
var LoBs = new List<LoB>();
// Assign some parameters to your objects
var exampleItem = new LoB();
exampleItem.Description = "Option text";
exampleItem.Value = "myValue";
// Populate your list and return your view.
LoBs.Add(exampleItem);
ViewBag.LoBs = LoBs;
return View();
查看:
@Html.DropDownList("Test",
new SelectList(ViewBag.LoBs, "Value", "Description"),
"--none--")
的Et瞧...
<select id="Test" name="Test">
<option value="">--none--</option>
<option value="myValue">Option text</option>
</select>
这篇关于拉的SelectList信息来源ViewBag:不创造价值=&QUOT; ...&QUOT;在生成html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!