带有asp.net mvc下拉列表的modelbinder

时间:2009-01-08 11:13:57

标签: asp.net-mvc

这是我正在尝试做的事情:

我有一个实体任务,其中包含TaskName属性和 TaskPriority 属性。

现在,在html中我有:

<td><%=Html.TextBox("Task.TaskName") %></td>
<td><%=Html.DropDownList("Task.TaskPriority",new SelectList(ViewData.Model.TaskPriorities,"ID","PriorityName")) %></td>

Controller操作如下:

public ActionResult Create(Task task){
    //task.TaskName has the correct value
    //task.TaskPriority is null - how should the html look so this would work ?
}

修改 在下面的示例中(来自Schotime):

public class Task
{
    public int name { get; set; }
    public string value { get; set; } // what if the type of the property were Dropdown ?
       // in the example I gave the Task has a property of type: TaskPriority.
}

1 个答案:

答案 0 :(得分:-1)

这应该有用。

三个班级:

    public class Container
    {
        public string name { get; set; }
        public List<Dropdown> drops { get; set; }
    }

    public class Dropdown
    {
        public int id { get; set; }
        public string value { get; set; }
    }

    public class Task
    {
        public int name { get; set; }
        public TaskPriority priority { get; set; }
    }

    public class TaskPriority
    {
        public string value { get; set; }
        ...
    }

控制器:

    public ActionResult Tasks()
    {
        List<dropdown> ds = new List<Dropdown>();
        ds.Add(new Dropdown() { id = 1, value = "first" });
        ds.Add(new Dropdown() { id = 2, value = "second" });

        ViewData.Model = new Container() { name = "name", drops = ds };

        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Tasks(Task drops)
    {
        //drops return values for both name and value
        return View();
    }

查看:强类型Viewpage<Container>

<%= Html.BeginForm() %>
<%= Html.TextBox("drops.name") %>
<%= Html.DropDownList("drops.priority.value",new SelectList(ViewData.Model.drops,"id","value")) %>
<%= Html.SubmitButton() %>
<% Html.EndForm(); %>

当我调试它时按预期工作。 如果你有类似的东西,不确定你做错了什么。 欢呼声。