Getting values ​​from asp.net mvc dropdown

Can someone help me get the values ​​from the dropdown in asp.net mvc?

I can get values ​​from text fields, etc., but how do I get these 2 things ...

  • Getting the selected value of a drop-down list item from a controller class
  • Retrieving an entire list of dropdown items from a controller class

thanks

+2
source share
3 answers

You can get the selected value from the drop-down list in the same way as for text fields.

Using default model binding

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
  //MyList will contain the selected value
  //...
}

or from FormCollection

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(FormCollection form) {
  string val = form["MyList"];
  //...
}

or from request

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
  string val = Request.Form["MyList"];  //or
  val = Request["MyList"];
  //...
}

If your dropdown is called "MyList".

<%= Html.DropDownList("MyList", MyItems) %>

or direct HTML

<select name="MyList">
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
</select>

, . , , , ( Html.DropDownList()).

[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample() {
  ViewData["MyItems"] = GetSelectList();
  return View();
}

[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample(string MyList) {
  //MyList contains the selected value
  SelectList list = GetSelectList(); //list will contain the original list of items
  //...
}

private SelectList GetSelectList() {
  Dictionary<string, string> list = new Dictionary<string, string>();
  list.Add("Item 1", "1");
  list.Add("Item 2", "2");
  list.Add("Item 3", "3");
  return new SelectList(list, "value", "key");
}

//...

<%= Html.DropDownList("MyList", ViewData["MyItems"] as SelectList) %>
+15

, , post .

- :

:

  //instantiate the dropdownlist in the controller method.
  public ActionResult Create() {
     List<string> items = new List<string>() {"first", "second", "third"};
     SelectList SomeSelectItems = new SelectList(items);
     ViewData["list"] = SomeSelectItems;
    return View();      
  }
  <%= Html.DropDownList("DDL", (SelectList)ViewData["list"]) %>

:

 [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(string DDL)
    {
        string theValue = DDL;
        return View();
    }

, , . , , . .

+1

, . , . . , .

+1

All Articles