2010-03-30 64 views
0

我在表单中使用incremental sequencing for a collection of objects。除了当我需要使用DropDownListFor时,所有的工作都很好,并且很漂亮。很多questions concerning binding a dropdown和选择正确的值,这在我的情况下工作正常。然而,我不清楚应该在我的控制器中的HttpPost动作。这里是我的代码:递增排序DropDownListFor绑定?

型号

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? 
} 

的dropdo列表填充得很好,他们得到预选就好了。但在发表回复form.Requests.AssignedTo为空。我假设车辆ID被调回地方,但我如何才能到,而不诉诸通过Request魔术字符串循环:

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

回答

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.... 
} 

我会敏锐地看到,如果有一个更直接的路线,因为这一直困扰着我。

+0

我写了一个巨大的丑陋模型绑定器,我正在使用。这看起来像一个更好的方法,会尝试一下。 – mxmissile 2010-03-31 13:41:58

+0

这太酷了,谢谢,让MVC变得更加简单。 – mxmissile 2010-03-31 14:53:32