views:

74

answers:

2

Hello,

In my model, I have this :

 public class CustomerModel
    {
        public Customer Customer { get; set; }
        public Language Language { get; set; }

        public IList<Language> Languages { get; set; }

        public CustomerModel()
        {
            Language = new Language();
        }
    }

In my view, I have this :

<%: Html.DropDownList("Id", new SelectList(Model.Languages, "Id", "Code"))%>

that's work

But I'd like when I do a submit, have the Model.Language.Id setted to the value selected I tried this, but not work :

<%: Html.DropDownList(m => m.Language.Id, new SelectList(Model.Languages, "Id", "Code"))%>

Updat1: I used this solution, ok working

<%: Html.DropDownList("Language", 
new SelectList(ViewData.Model.Languages, "Id", "Code")) %>

When I select a customer, I'd like see the language change depending customer language, I did this :

<%: Html.DropDownList("Language", new SelectList(ViewData.Model.Languages, "Id", "Code", ViewData.Model.Customer.Language.Id)) %> 

nothing happen, I still see the first language of the list and not the customer language. The data in the controller are correct

Thanks,

A: 

This works fine for me (you need to use Html.DropDownListFor helper if you want to pass a lambda expression):

Model:

public class Language
{
    public int Id { get; set; }
    public string Code { get; set; }
}

public class CustomerModel
{
    public Language Language { get; set; }
    public IList<Language> Languages { get; set; }

    public CustomerModel()
    {
        Language = new Language();
        Languages = new List<Language>
        {
            new Language { Id = 1, Code = "en" },
            new Language { Id = 2, Code = "fr" },
        };
    }
}

Controller:

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

    [HttpPost]
    public ActionResult Index(CustomerModel model)
    {
        return View(model);
    }
}

View:

<% using (Html.BeginForm()) { %>
    <%: Html.DropDownListFor(
        x => x.Language.Id, 
        new SelectList(Model.Languages, "Id", "Code")
    ) %>
    <input type="submit" value="OK" />
<% } %>
Darin Dimitrov
I added a comment see "Update1"
Kris-I
+1  A: 

use strongly typed html helper DropDownListFor

<%: Html.DropDownListFor(m => m.Language.Id, new SelectList(Model.Languages, "Id", "Code"))%>
Muhammad Adeel Zahid
I added a comment see "Update1"
Kris-I
does Model.Languages contain Model.Customer.Language object?
Muhammad Adeel Zahid
Model.Languages has the languages possible (3 in my case) Model.Customer.Language is not null and has the value of one of the 3
Kris-I
then only thing i can imagine is that model.customer.language is being reset somewhere down the line. can u put controller code
Muhammad Adeel Zahid