DataBinding a DropDownList in ASP.NET MVC 2
I'm extremely frustrated trying to switch to MVC after a couple years of webforms development.
Here's my extremely simple problem that I can't manage to solve: I have a list of States in a table called StateProvince. I have a DropDownList. I want the DropDownList to display all of the States.
Keep it simple, I know nothing about MVC.
Here's what I have. All this gives me is a DropDownList filled with "System.Web.Mvc.SelectListItem".
Action:
public ActionResult Create()
{
var dbTimecard = new TimecardDbDataContext();
IEnumerable<SelectListItem> statePr开发者_StackOverflow社区ovinces = dbTimecard.StateProvinces.Select(p => new SelectListItem
{
Value = p.StateProvinceId.ToString(),
Text = p.Name
});
SelectList theList = new SelectList(stateProvinces);
ViewData["StateProvince"] = theList;
return View();
}
View:
<div class="editor-label">
<%: Html.LabelFor(model => model.StateProvinceId) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.StateProvinceId, (SelectList)ViewData["StateProvince"])%>
<%: Html.ValidationMessageFor(model => model.StateProvinceId) %>
</div>
Here is what I was looking for:
Action:
public ActionResult Create()
{
var dbTimecard = new TimecardDbDataContext();
IEnumerable<SelectListItem> stateProvinces = dbTimecard.StateProvinces.Select(p => new SelectListItem
{
Value = p.StateProvinceId.ToString(),
Text = p.Name
});
ViewData["StateProvince"] = stateProvinces;
return View();
}
View:
<div class="editor-field">
<%: Html.DropDownListFor(model => model.StateProvinceId, (IEnumerable<SelectListItem>)ViewData["StateProvince"])%>
<%: Html.ValidationMessageFor(model => model.StateProvinceId) %>
</div>
Try replacing this
SelectList theList = new SelectList(stateProvinces);
with this...
SelectList theList = new SelectList(stateProvinces, "Value", "Text");
Common browsers don't support PUT
verb within HTML forms. You might need to handle this using ajax:
$(function() {
// when some button is clicked:
$('#someButton').click(function() {
$.ajax({
url: '/controller/action',
data: { selectedState: $('#StateProvinceId').val() },
type: 'PUT',
success: function(data) {
alert('state successfully submitted');
}
});
return false;
});
});
When the data is posted, the items listed in the DropDown
are not posted back to the model so I am assuming you are not fetching them again and re-adding them to your model before returning your model back to the view.
You need to make sure on your post that you are filling Model.StateProvinces
and then passing it to your View. Only the values are persisted unlike WebForms which would maintain the DropDownList
items in the ViewState
and rebuild them for you.
So assuming your controller looks something like:
// POST: /YourController/YourAction/{ID}
[HttpPost]
public ActionResult YourAction(YourModel model, int id)
{
// model.StateProvinceId has the selected value
// you need to fill StateProvinces since it is empty as the list is not posted
// back so it is not autofilled into your model.
model.StateProvinces = LoadYourStateProvincesList();
// This would blow up if StateProvinces is null because your View is assuming that
// it has a valid list of StateProvinces in it to build the DropDown
return View(model);
}
I actually asked a question a while back that might be of some use to help explain how to handle DropDown lists:
Best way of implementing DropDownList in ASP.NET MVC 2?
EDIT: Based on your comment it you are not even getting the first list up... well it looks like you might not have your model setup correctly. Do you even have a model? Your create is just returning View()
with no model data in it. You need to create a Model and return it.
Eg.
public class YourModel
{
public int StateProvinceId { get; set; }
/// ... whatever else you need
}
// Then in your view your controller you need to set it and create it
View(new YourModel() { StateProvinceId = 123 };);
You need the model so that when the form IS posted back you can retrieve the value because MVC will stuff the value into your model like th example I posted above regarding the POST part.
EDIT: Ok now that question is clearer and a lot simpler than the original question was making the problem out to be. The problem is your SelectList needs tell it which fields to put where:
SelectList theList = new SelectList(stateProvinces, "Value", "Text");
In your original question you had:
<%: Html.DropDownListFor(model => model.StateProvinceId, new SelectList(Model.StateProvinces, "StateProvinceId", "Name") )%>
Which was totally correct but it was how you were building up Model.StateProvinces that was wrong so it threw me off thinking it had to be something else.
精彩评论