开发者

Dropdownlist in ASP.NET MVC2

开发者 https://www.devze.com 2023-01-17 08:23 出处:网络
In my model, I have this : public class CustomerModel { public Customer Customer { get; set; } public Language Language { get; set; }

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开发者_如何学JAVA.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,


use strongly typed html helper DropDownListFor

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


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" />
<% } %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号