简体   繁体   中英

getting the value of dropdownlist in MVC4

i am new to MVC Tell me how can i retrieve the selected dropdownlist value in controller this is how i add the values to dropdownlist

List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "What is your Place of Birth?", Value = "What is your Place of Birth?" });
            items.Add(new SelectListItem { Text = "What is your favourite Book?", Value = "What is your favourite Book?" });
            items.Add(new SelectListItem { Text = "What is your childhood friend name?", Value = "What is your childhood friend name?" });
            items.Add(new SelectListItem { Text = "What is your first car make and model?", Value = "What is your first car make and model?" });
            items.Add(new SelectListItem { Text = "What is your favourite place?", Value = "What is your favourite place?" });
            ViewData["ddlitems"] = items;

VIEW FILE

@Html.DropDownList("ddlitems")

On your model, have a property for the value:

class ModelClass
{
    public string DropdownValue{get; set;}
}

Then use the following Razor syntax

@Html.DropdownListFor(m => m.DropdownValue, "ddItems");

That will create a dropdown named the same as the Model property, it should automatically post back with the model

The most simple way to get the value of the selected option is just to match the ID of the element to that which you are posting to the ActionResult . So if your select element is rendered as;

<select id="SomeID">
    <option value="What is your Place of Birth?">What is your Place of Birth?</option>
</select>

Then you post this to an ActionResult

[HttpPost]
public ActionResult MyActionResult(string SomeID){
    // SomeID = What is your Place of Birth?
    Return View();
}

This might be the easiest option in your case because you do not have a strongly typed object which you are passing into the View . Also note that this will work with any form elements that you are posting. Just match up the IDs with parameters on the ActionResult .

To take this further, you would probably be best reading about Model Binding within ASP.Net MVC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM