Question about ASP.NET MVC and DropDown Lists

I am going to launch a new ASP.NET MVC application. In it, we have several drop-down lists / boxes. I have no problem using their ui, etc.

My two questions: -

  • Is it possible to associate the selected value of a drop-down list with an enumeration? Does anyone else do this (if possible)
  • Are there any good code methods to prevent the code from throwing an exception if the user tries to enter a different value for the drop-down list. For instance. instead of setting the selected value, which is the number / int .., they try to crack the mail data and change it to the string non numbers. And what is this security hack / use called?

cheers :)

+3
source share
2 answers

As posted by jfar, use:

string selectedValue = "1";

SelectListItem[] selectListItems = Enum.GetNames(typeof(MyEnumeration)).Select(
        s => new SelectListItem { Text = s, Value = s, Selected = s == selectedValue}).ToArray();

which of MVCContrib, you should not include a DLL, this is just the code found in MVCContrib.

To protect against CSRF (Cross-Site Request Subroutine), you can use <%= Html.AntiForgeryToken() %>the presentation in the appropriate form to be placed and decorate the corresponding action with [ValidateAntiForgeryToken]. More information about Html.AntiForgeryToken()can be found here .

EDIT According to comment

Ok, first you need to put SelectListItem[]in ViewData so that you can access it in the view:

Act

[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();    
}

and, in your opinion, the following form will work.

<form method="post">
    <%= Html.AntiForgeryToken() %>
    <%= Html.DropDownList("enumValue") %>
</form>

HTML- select.

, ,

[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();    
}
+3

MVCContrib:

SelectListItem[] selectListItems = Enum.GetNames(propertyInfo.PropertyType).Select(
            s => new SelectListItem {Text = s, Value = s, Selected = s == value.ToString()}).ToArray();

, : http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/mvc/tutorial-24-cs.aspx

, .

+1

Source: https://habr.com/ru/post/1731953/


All Articles