【发布时间】:2014-04-10 13:50:11
【问题描述】:
我有一个控制器响应如下 URL:
http://localhost:64121/BrowseNode/Create/1016?nodeTypeId=Category
错误:NodeTypeId 下拉列表未选择所需元素(id 为 3)。
动作方法(第3项选择失败):
public ActionResult Create([Bind(Prefix = "id")]int? parentBrowseNodeId, Enums.eNodeType? nodeTypeId)
{
int typeId = (int)nodeTypeId.GetValueOrDefault(Enums.eNodeType.Category);
// 3 is hard-wired to test this bug - still does not work
ViewBag.NodeTypeId = new SelectList(db.NodeType, "NodeTypeId", "LabelEN", 3);
ViewBag.OwnerUserId = new SelectList(db.User, "UserId", "EmailAddress", 3);
return View(new CreateItemVM()
{
OwnerUserId = 3,
NodeTypeId = (int)nodeTypeId
});
}
如果我调试实际代码,nodeTypeId 参数的值为“类别”,然后变为 3,但我使用的是硬连线值,但它仍然失败。
如果我使用int 参数而不是枚举,则使用此 URL:
http://localhost:64121/BrowseNode/Create/1016?nodeTypeId=3
带int参数的动作方法(有效):
// GET: /BrowseNode/Create
public ActionResult Create([Bind(Prefix = "id")]int? parentBrowseNodeId, int nodeTypeId)
{
ViewBag.NodeTypeId = new SelectList(db.NodeType, "NodeTypeId", "LabelEN", 3);
ViewBag.OwnerUserId = new SelectList(db.User, "UserId", "EmailAddress", 3);
return View(new CreateItemVM()
{
OwnerUserId = 3,
NodeTypeId = 3
});
}
视图 Create.cshtml 有两个下拉菜单,如:
<div class="form-group">
@Html.LabelFor(model => model.NodeTypeId, "NodeTypeId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("NodeTypeId")
@Html.ValidationMessageFor(model => model.NodeTypeId)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.OwnerUserId, "OwnerUserId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("OwnerUserId")
@Html.ValidationMessageFor(model => model.OwnerUserId)
</div>
</div>
问题:
为什么代码可以使用 int 参数,但使用 enum 会失败,即使列表的实际选择值硬连线为 3?
更新:
这个问题纯粹归结为使用名称nodeTypeId作为枚举的参数名称。如果我将其重命名为 nodetype 并将网址更改为 http://localhost:64121/BrowseNode/Create/1016?nodeType=Category 它可以工作!
看起来参数名称以某种方式传递到视图并覆盖了默认值。我不知道参数会自动从控制器传递给 MVC 视图。谁能解释一下为什么?
【问题讨论】:
标签: asp.net-mvc razor query-string selectlist viewbag