Reputation: 428
How do I get the selected value sent from the dropdownlist on the view from the controller?
Model:
public class CustomerInformation
{
public Dictionary<int, string> State { get; set; }
public CustomerInformation()
{
State = new Dictionary<int, string>()
{
{ 0, "California"},
{ 1, "Nevada"}
};
}
}
Controller
public ActionResult Index()
{
var model = new CustomerInformation.Models.CustomerInformation();
return View(model);
}
public ActionResult ShowData(CustomerInformation.Models.CustomerInformation _customerInformation)
{
//..
}
View
@using (Html.BeginForm("ShowData", "Home"))
{
@Html.Label("State:: ");
@Html.DropDownListFor(m => m.State, new SelectList(Model.State, "Key", "Value"))
<input type="submit" value="Submit" />
}
Upvotes: 1
Views: 87
Reputation: 428
I needed to add to my model
public int id { get; set; }
to hold the imputed selected dropdown value
then in my view assign that value
@Html.DropDownListFor(m => m.id, new SelectList(Model.State, "Key", "Value"))
Upvotes: 0
Reputation: 5443
You need a StateId
property for your model. Then you can get that in your posted value...
public class CustomerInformation
{
public Dictionary<int, string> State { get; set; }
public int StateId {get;set;}
public CustomerInformation()
{
State = new Dictionary<int, string>()
{
{ 0, "California"},
{ 1, "Nevada"}
};
}
}
This is where you'll want to change the id and name of your html select list:
@Html.DropDownListFor(m => m.StateId, new SelectList(Model.State, "Key", "Value"))
Then in your Post method:
public ActionResult ShowData(CustomerInformation.Models.CustomerInformation _customerInformation)
{
_customerInformation.StateId // The selected value.
}
Upvotes: 1