1

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> stateProvinces = 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>
Daniel Coffman
  • 1,997
  • 3
  • 26
  • 34
  • is the Model.StateProvinces actually filled with objects AND the StateProvinceId contains a non-null value AND the model != null? – Michel Apr 15 '10 at 20:11
  • Can you show the action? – Mathias F Apr 15 '10 at 20:12
  • Ok I assume Create is your GET... where is the code that handles the post and returns the result? That is where I think the problem is and ViewData is not persisted between calls but I could be totally misinterpreting the question. Is the problem on initial load or after you post your results and are rebuilding the view? – Kelsey Apr 15 '10 at 20:52
  • Yes, this is the GET. Forget the POST. I shouldn't even have mentioned the POST. I can't even populate the DropDownList. How do I populate the DropDownList? Allow me to clarify: I want a DropDownList to show some values from a Database. How do I make this happen? – Daniel Coffman Apr 15 '10 at 20:54
  • I know MVC can be hard to get your head around, but keep at it! It's well worth it once you figure out how things work. – Mac Apr 15 '10 at 23:31

4 Answers4

1

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>
Daniel Coffman
  • 1,997
  • 3
  • 26
  • 34
  • 1
    There is no model being assigned to the view so how is `model => model.StaeProvinceId` suppose to work? Check out the edit I made to my answer. – Kelsey Apr 15 '10 at 21:15
1

Try replacing this

SelectList theList = new SelectList(stateProvinces);

with this...

SelectList theList = new SelectList(stateProvinces, "Value", "Text");
Casey Williams
  • 4,045
  • 2
  • 24
  • 15
0

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;
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

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.

Community
  • 1
  • 1
Kelsey
  • 47,246
  • 16
  • 124
  • 162