增量排序DropDownListFor Binding?

时间:2010-03-30 17:33:00

标签: asp.net-mvc asp.net-mvc-2 html.dropdownlistfor

我在表单中使用incremental sequencing for a collection of objects。除非我需要使用DropDownListFor,否则所有工作都很好并且花花公子。很多questions concerning binding a dropdown并选择正确的值,这在我的情况下运行正常。但是我不知道我的控制器中的HttpPost动作应该有什么。这是我的代码:

模型

public class WorkRequestList
{
    public WorkRequest[] Requests { get; set; }
    public Vehicle[] Vehicles { get; set; }       
}

查看

 <% using (Html.BeginForm()) {%>
     <% for (var i = 0; i < Model.Requests.Count(); i++) { %>
        <%=Html.DropDownListFor(x => x.Requests[i].AssignedTo,new SelectList(Model.Vehicles,"Id","Name",Model.Requests[i].AssignedTo.Id)) %>
      <%}%>
 <%=Html.SubmitButton("TopSubmit","Submit") %>
<%}%>

已发布行动

[HttpPost]
public ActionResult Schedule(WorkRequestList form)
{
      //what goes here?
}

下拉列表填充得很好,他们预先选好了。但是在post back form.Requests.AssignedTo为null。我假设车辆ID正在某处发回,但是我如何在没有通过Request魔术字符串循环的情况下达到目的:

var id = Request["Requests[" + i + "].AssignedTo"];

1 个答案:

答案 0 :(得分:1)

这是一种替代方法,因为如果没有明确的模型绑定器,我无法绑定子对象:

为您的回复定义一个新类:

public class WorkRequestResponse 
{
    public int AssignedTo { get; set; }
}

在页面上更改如下:(我将请求更改为WorkRequest)

<% for (var i = 0; i < Model.WorkRequest.Count(); i++)
       { %>
    <%=Html.DropDownListFor(x => x.WorkRequest[i].AssignedTo, new SelectList(Model.Vehicles, "Id", "Name", Model.WorkRequest[i].AssignedTo.Id))%>
    <%}%>

在您的控制器上绑定如下:

public ActionResult Index([Bind(Prefix = "WorkRequest")]List<WorkRequestResponse> AssignedTo)
{
    // AssignedTo is now populated
    WorkRequestList.WorkRequests = magic_assign_function(AssignedTo); 
    // manual model validation etc....
}

我很想知道是否有更直接的路线,因为这也困扰着我。