How to receive selected Dropdownlist value in [HttpPost] method?
And again a newbie question. ;-)
I am setting my View Model based on this very helpfull post:
public class My_IndexModel
{
...
public IEnumerable<SelectListItem> My_DropDownList { get; set; }
...
}
Please note that I use
IEnumerable<SelectListItem>
to be able to set the Selected Property.
The dropdown list values are set in the controller:
public ActionResult Index()
{
...
var DropDownList_Values = from value in My_DB.Value
select new SelectListItem
{
开发者_如何学PythonSelected = (value.IsDefault == 1),
Text = value.Value1,
Value = value.Value1
};
...
var viewModel = new My_IndexModel
{ ...
My_DropDownList = DropDownList_Values.ToList(),
...
}
...
return View(viewModel);
}
Means my ViewData model contains (in my case) a dropdownlist.
Also the dropdownlist is in my site (*.aspx) shown and look so:
<%: Html.DropDownList("MyDropDownListField",
new SelectList(Model.My_DropDownList as IEnumerable,
"Value",
"Text",
Model.My_DropDownList
)
)%>
No problem up to this point.
On the website (*.aspx) I have a simple "submit" button which returns all datas. I fetch the submit event here:
[HttpPost]
public ActionResult Index(My_IndexModel model)
{
if (ModelState.IsValid)
{
... model.My_DropDownList ...
}
}
But the DropDownList is empty!
What must be done to get the selected dropdownlist value in the [HttpPost] method?
You need to add a property with the same name as the DropDownList
to the model you are using in the controller that is recieving the post. If the names match up, the framework will put the selected value into the matching model property.
You should look at using Html.DropDownListFor
helper.
For more information see this question I posted a while back when I had issues figuring out the best way to implement a DropDownList in MVC:
Best way of implementing DropDownList in ASP.NET MVC 2?
精彩评论