Reputation: 6762
I have a simple form in Asp.Net MVC form and I had a dropdown list with values pulled from a view data. How can I get the value of selected value from dropdown to the controller object to use inside httppost method?
@Html.LabelFor(model => model.ItemType)
@Html.DropDownList("ItemTypes", new SelectList((IEnumerable)ViewData["itemTypes"], "Value", "Text"))
<input type="submit" value="Request Item" />
ViewData["itemTypes"] = GetItemTypes();
[HttpPost]
public ActionResult NewVc(ItemInfoViewModel itemInfoObject)
{
//Item not populated to itemInfoObject
}
Pull Item types from
public static List<ListItem> GetItemTypes()
{
var itemTypes = new List<ListItem>
{
new ListItem {Text = "Select", Value = ""},
new ListItem {Text = "Item1", Value = "Item1"},
new ListItem {Text = "Item2", Value = "Item2"},
new ListItem {Text = "Item3", Value = "Item3"}
};
return itemTypes;
}
Upvotes: 0
Views: 3259
Reputation: 218702
If not exist, add a new property to store the selected option
public class ItemInfoViewModel
{
public string SelectedItemType { set;get;}
// your existing properties
}
Now in your GET action method, you can use the Html.DropDownListFor
helper inside the form.
@model ItemInfoViewModel
@using(Html.BeginForm("NewVc","PutYourControllerNameHere"))
{
@Html.DropDownListFor(s=>s.SelectedItemType,
ViewData["itemTypes"] as List<SelectListItem>)
<input type="submit" />
}
Replace PutYourControllerNameHere with your actual controller name where you have the NewVc
action method. You do not need the Controller
Suffix.
The above code basically generates the HTML tag for a SELECT element with name "SelectItemType
" inside a form
tag. When you submit the form, model binder will be able to map the posted form data to the property of your ItemInfoViewModel
object, which is the parameter of your HttpPost action method.
Also you should change the return type of
your GetItemTypes
method to a collection of SelectListItem
since our view code is trying to cast it directly a List<SelectListItem>
public static List<SelectListItem> GetItemTypes()
{
var itemTypes = new List<SelectListItem>
{
new SelectListItem{Text = "Select", Value = ""},
new SelectListItem{Text = "Item1", Value = "Item1"},
new SelectListItem{Text = "Item2", Value = "Item2"},
new SelectListItem{Text = "Item3", Value = "Item3"}
};
return itemTypes;
}
Upvotes: 2