views:

85

answers:

1

Hello,

I try to make a view in ASP.NEt mvc 2 with a selectList.

I fill up the selectlist languages from my model (regDom)

listLangModel is a list of languages I retrieve from the database.

regDom.Languages = from l in listLangModel

               select new SelectListItem
                     {
                        Text = l.Name,
                        Value = l.ID
                     };

In my view I have this

        <div class="editor-label">
            <%: Html.LabelFor(model =>> model.Languages) %>
        </div>
        <div class="editor-field">
            <%: Html.DropDownListFor(model =>  model.Languages, Model.Languages) %>
            <%: Html.ValidationMessageFor(model => model.Languages) %>
        </div>

When I run, the languages are in the dropdownlist on my page. But when I post it back to my server, the model doesn't contain the languages anymore. And I can't check which language is selected on the page.

+1  A: 

The user can select only a single language from the drop down list, so you cannot expect it to populate the Languages property of your model which is a collection.

Add a property to hold the selected language in your model:

public string SelectedLanguage { get; set; }

and then bind the drop down list to this property:

<%: Html.DropDownListFor(model => model.SelectedLanguage, Model.Languages) %>
Darin Dimitrov
Thank you, now can I see which language is chosen.But can I pass also my languages back. In case there is some input that is not valid (because of business rules), I can give back my form with all the languages?
Masna
Yes, you pass the model to the view (`return View(model)`) which has the `Languages` property containing all the languages allowing you to rebind the drop down list.
Darin Dimitrov
Thx for the quick answer. But I get this error now: The ViewData item that has the key 'SelectedLanguage' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.And when I debug, my languages variable of my object is empty when it comes back.
Masna
Maybe for safety reasons it's better i refill my dropdownlist with the correct data before I return it back to the user.
Masna