ASP.NET MVC2中的下拉列表

时间:2010-09-25 10:43:17

标签: c# asp.net-mvc asp.net-mvc-2

在我的模型中,我有这个:

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

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

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

在我看来,我有这个:

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

这是工作

但是当我提交时,我想将Model.Language.Id设置为所选值 我试过了,但没有工作:

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

Updat1: 我用这个解决方案,好的工作

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

当我选择客户时,我希望根据客户语言看到语言的变化,我这样做了:

<%: Html.DropDownList("Language", new SelectList(ViewData.Model.Languages, "Id", "Code", ViewData.Model.Customer.Language.Id)) %> 
什么都没发生,我仍然看到列表的第一语言,而不是客户语言。控制器中的数据是正确的

谢谢,

2 个答案:

答案 0 :(得分:1)

使用强类型的html助手DropDownListFor

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

答案 1 :(得分:0)

这对我来说很好(如果你想传递lambda表达式,你需要使用Html.DropDownListFor助手):

型号:

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" },
        };
    }
}

控制器:

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

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

查看:

<% using (Html.BeginForm()) { %>
    <%: Html.DropDownListFor(
        x => x.Language.Id, 
        new SelectList(Model.Languages, "Id", "Code")
    ) %>
    <input type="submit" value="OK" />
<% } %>