我要启动一个新的 ASP.NET MVC 应用程序。在其中我们有许多下拉列表/框。我可以毫无问题地将它们发送到 ui 等。
我的两个问题是:-
- 是否可以将下拉列表的选定值绑定(bind)到枚举?有没有其他人真的这样做(如果可能的话)
- 如果用户尝试为下拉菜单注入(inject)不同的值,是否有任何好的代码实践可以防止代码抛出异常。例如。而不是发布选定的值(数字/整数).. 他们尝试破解发布数据并将其更改为非数字字符串。这种安全黑客/漏洞利用的名称是什么?
干杯:)
最佳答案
正如 jfar 发布的那样,使用:
string selectedValue = "1";
SelectListItem[] selectListItems = Enum.GetNames(typeof(MyEnumeration)).Select(
s => new SelectListItem { Text = s, Value = s, Selected = s == selectedValue}).ToArray();
它来自 MVCContrib,您不需要包含 DLL,这只是在 MVCContrib 中找到的代码。
防止CSRF (跨站请求伪造),你可以使用 <%= Html.AntiForgeryToken() %>
在将发布的相应表单下的 View 中,并使用 [ValidateAntiForgeryToken]
装饰适当的操作.有关 Html.AntiForgeryToken()
的更多详细信息可以是found here .
根据评论编辑
首先,您需要放置 SelectListItem[]
在 ViewData 中,以便您可以在 View 中访问它:
Action
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult MyView(string enumValue)
{
string selectedValue = "1"; // fill this with the value you want to be selected
SelectListItem[] selectListItems = Enum.GetNames(typeof(MyEnumeration)).Select(
s => new SelectListItem { Text = s, Value = s, Selected = s == selectedValue}).ToArray();
ViewData["enumValue"] = selectListItems;
return View();
}
在您看来,以下表格将有效。
<form method="post">
<%= Html.AntiForgeryToken() %>
<%= Html.DropDownList("enumValue") %>
</form>
HTML 助手将输出正确的 select
控制。
回到您的 Controller 中,这是将接受表单发布的操作
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyView(int enumValue)
{
// enumValue will have the selected value
ViewData["Message"] = "You selected the Enum name" + Enum.GetName(typeof(MyEnumeration), enumValue);
return View();
}
关于.net - 关于 ASP.NET MVC 和下拉列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2226166/