使用HttpPost传递IEnumerable或将Model列表到Controller

时间:2011-08-10 09:39:59

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

我有这个问题:

我的模特

public class SpesaTrasportoView
{ 
    public int SPESATRASPORTOVIEW_ID;
    public decimal PREZZO;
    public string DESCRIZIONE;
}

public class SpeseTrasportoView
{
    public List<MvcCart.Models.SpesaTrasportoView> SpeseTrasportoModello { get; set; }
    //public IList<string> Spese  { get; set; }
}

我的观点

@model MvcCart.Models.SpeseTrasportoView
@{
    ViewBag.Title = "Spese Trasporto";
    int counter = 0;
}

<div class="form-content">
<h2>Spese Trasporto</h2>
<p>
   Modifica e gestisci gli importi delle spese di trasporto.     
</p>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {

    <div class="data-content">
        <fieldset>
            <legend>Informazione Spese Trasporto</legend>
            @for (int i = 0; i < Model.SpeseTrasportoModello.Count; i++)
            {
                 <div class="editor-field">
                    @Html.TextBoxFor(m => m.SpeseTrasportoModello.ToList()[i].PREZZO)
                 </div>
            }


            <p>
               <input type="hidden" value="@ViewBag.FormStatus" id="Action" name="Action"/>
               <input type="submit" value="Salva" id="Salva" name="Salva"/>
            </p>
        </fieldset>
    </div>
}

</div>

我的控制器

[HttpPost]
public ActionResult SpeseTrasporto(SpeseTrasportoView model)
{
    //model.SpeseTrasportoModello is ever NULL :(((((
    return View();
}

当我提交模型时.SpeseTrasportoModello为null!为什么mvc3不绑定数据????

1 个答案:

答案 0 :(得分:6)

您需要解决一些问题。首先为您的模型,制作一切属性。不要使用字段。

型号:

public class SpesaTrasportoView
{
    public int SPESATRASPORTOVIEW_ID { get; set; }
    public decimal PREZZO { get; set; }
    public string DESCRIZIONE { get; set; }
}

public class SpeseTrasportoView
{
    public List<SpesaTrasportoView> SpeseTrasportoModello { get; set; }
}

现在,在视图中更改for循环,使其如下所示:

@for (int i = 0; i < Model.SpeseTrasportoModello.Count; i++)
{
    var item = Model.SpeseTrasportoModello[i];

    <div class="editor-field">
        <input type="text" 
               name="SpeseTrasportoModello[@i].PREZZO" 
               value="@item.PREZZO" />
    </div>
}

您需要知道的关键是输入名称格式。它应该具有模型内部属性的名称(列表),方括号中带有索引,然后是此输入所用属性的名称(例如PREZZO)。