views:

53

answers:

2

I'm creating a drop down via

<%= Html.DropDownList("data.Language", Model.LanguageOptions) %>

and want to read back its value through automatic model binding into my LanguageModel viewmodel:

public ActionResult Save(LanguageModel data)

However, data.Language is null when the Save method is called.

How do I get the selected value from my data.Language dropdown into data.Language?

A: 

get rid of the data.

<%= Html.DropDownList("Language", Model.LanguageOptions) %>

Or try:

<%= Html.DropDownListFor(m => m.Language, Model.LanguageOptions) %>

(although m.Langage may not be right - it depends on how your view model is set up)

thekaido
Getting rid of data doesn't work.
Alex
A: 

I don't know how your controller action and model look like but this definitely works:

Model:

public class LanguageModel
{
    public string Language { get; set; }
    public IEnumerable<SelectListItem> LanguageOptions
    {
        get
        {
            return new[] 
            {
                new SelectListItem { Value = "en", Text = "English" },
                new SelectListItem { Value = "fr", Text = "French" },
            };
        }
    }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new LanguageModel());
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(LanguageModel data)
    {
        return View(data);
    }
}

View:

<% using (Html.BeginForm()) { %>
    <%= Html.DropDownList("Language", Model.LanguageOptions) %>
    <input type="submit" value="OK" />
<% } %>

<div><%= Html.Encode(Model.Language) %></div>

Of course if you are using ASP.NET MVC 2.0, the strongly typed DropDownListFor helper is preferable.

Darin Dimitrov
It appears that my issue is bigger than that. I used FireBug to check on the values, and they are in fact submitted correctly. I just don't have anything arriving in my action method (ViewData doesn't contain anything). Asked a separate question here once I found out that this is the underlying issue: http://stackoverflow.com/questions/2931805/asp-net-mvc-2-viewdata-empty-after-post
Alex
What do you expect to find in ViewData in a postback? It is used for the controller to send data to the view and not vice-versa. Look in `Request["data1"]` or even better in the parameters of the controller action.
Darin Dimitrov