Asp.net mvc 当MVC dropdownlist不是表的一部分时,如何使用IDictionary进行它
我有一些代码,在razor文件中的一个表中设置了dropdownlist,使用:Asp.net mvc 当MVC dropdownlist不是表的一部分时,如何使用IDictionary进行它,asp.net-mvc,asp.net-mvc-3,razor,drop-down-menu,idictionary,Asp.net Mvc,Asp.net Mvc 3,Razor,Drop Down Menu,Idictionary,我有一些代码,在razor文件中的一个表中设置了dropdownlist,使用: foreach (var item in group) { <tr> <td> ... @Html.DropDownListFor(modelItem => item.OfficeUserId, Model.OfficeApprovers, new { @class = "offic
foreach (var item in group) {
<tr>
<td>
...
@Html.DropDownListFor(modelItem => item.OfficeUserId, Model.OfficeApprovers, new { @class = "officeapproverddl", invoiceLineId = @item.InvoiceLineId, officeUserId = @item.OfficeUserId })
...
</td>
</tr>
}
</table>
这很有效,但是现在我希望在表外有相同的下拉列表。因此,将没有要使用的item对象
你是如何在表外完成这项工作的?我现在只需要提供Model.OfficeApprovers和html属性
Model.OfficeApprovers的类型为:new Dictionary 从这里我们可以看到DropDownListFor具有以下语法:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
Object htmlAttributes
)
因此,您想要的方式不是使用DropDownListFor
在这种情况下,最好使用simple@Html.DropDownList。您可以使用来实现您想要的:
public static MvcHtmlString DropDownList(
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList,
IDictionary<string, Object> htmlAttributes
)
编辑:
试试这个:
@Html.DropDownList("officeApprovers", Model.OfficeApprovers.Values[0],
new { @class = "officeapproverddl" }
你使用字典有什么原因吗 下面是填充下拉列表时通常执行的代码。这是非常简单的,我建议您使用它作为基础来构建下拉列表 在我的视图顶部,我指定我的视图模型:
@model MyProject.ViewModels.MyViewModel
在我的视图中,我有一个下拉列表,其中显示了用户可以从中选择的所有银行:
<table>
<tr>
<td><b>Bank:</b></td>
<td>
@Html.DropDownListFor(
x => x.BankId,
new SelectList(Model.Banks, "Id", "Name", Model.BankId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.BankId)
</td>
</tr>
</table>
然后,在我的操作方法中,我创建了视图模型的一个实例,并从数据库中填充banks列表。完成此操作后,我将视图模型返回到视图:
public ActionResult MyActionMethod()
{
MyViewModel viewModel = new ViewModel
{
// Database call to get all the banks
// GetAll returns a list of Bank objects
Banks = bankService.GetAll()
};
return View(viewModel);
}
我希望这会有所帮助。实际上不会起作用,因为我的selectList是Dictionary而不是IEnumerable类型。这本字典中有多少个键值对?在这种情况下,你为什么要用字典?似乎有点不对。。。你应该有充分的理由。
<table>
<tr>
<td><b>Bank:</b></td>
<td>
@Html.DropDownListFor(
x => x.BankId,
new SelectList(Model.Banks, "Id", "Name", Model.BankId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.BankId)
</td>
</tr>
</table>
public class MyViewModel
{
// Other properties
public int BankId { get; set; }
public IEnumerable<Bank> Banks { get; set; }
}
public class Bank
{
public int Id { get; set; }
public string Name { get; set; }
}
public ActionResult MyActionMethod()
{
MyViewModel viewModel = new ViewModel
{
// Database call to get all the banks
// GetAll returns a list of Bank objects
Banks = bankService.GetAll()
};
return View(viewModel);
}