2014-02-09 27 views
1

我有一个局部视图:数据是NULL

@model BasicFinanceUI.Models.TransactionLine 

<div class="form-group"> 
    <label for="cmbCategory0" class="col-lg-1 control-label">Category:</label> 
    <div class="col-lg-3"> 
     @Html.DropDownListFor(x => x.CategoryId, 
            new SelectList(Model.References.Categories, "Value", "Text", Model.CategoryId), "Select one", 
            new { @onchange = "populateSubCategory(0)", @class = "cmbCategory form-control" }) 
    </div> 
</div> 

这种部分视图是从对象的List <>装载在我的主视图:

@foreach (var line in Model.Transaction.TransactionLines) 
{ 
    @Html.Partial("_TransactionLine", line) 
} 

局部视图( s)加载正确,数据正确。

但是,当我想保存数据 - 看起来我的列表有一行,但行中没有数据。我是部分视图的新手,但似乎MVC不会将部分视图数据映射到创建部分视图列表的列表<>。

我做错了什么?

在控制器中,当我试图将数据读入我的对象送他们回数据库,我这样做:

item.TransactionLines = new List<TransactionLineDto>(); 
foreach (var line in model.Transaction.TransactionLines) 
{ 
    item.TransactionLines.Add(new TransactionLineDto 
     { 
      Id = line.Id, 
      CostCentreId = line.CostCentreId, 
      SubCategoryId = line.SubCategoryId, 
      TransactionId = model.Transaction.Id, 
      Amount = line.Amount 
     }); 
} 

但是,我所发现的是,所有的值都是0.看起来局部视图不会将数据返回到视图的模型。这是预期的行为,还是我做错了什么?

我试过'部分'和'渲染部分'。不知道为什么是正确的,因为它们都导致同样的问题。

回答

0

如果您检查HTML,您将看到部分内部下拉菜单的名称属性将为CategoryId。这是错误的,因为它应该是Transaction.TransactionLines[0].CategoryId。否则ASP.NET MVC将无法正确地将值映射到模型。解决这个问题的最简单的解决方案是使用for循环并在主视图中移动部分视图HTML。

for (int i = 0; i < model.Transaction.TransactionLines.Count; i++) 
{ 
    <div class="form-group"> 
     <label for="cmbCategory0" class="col-lg-1 control-label">Category:</label> 
     <div class="col-lg-3"> 
     @Html.DropDownListFor(x => x.Transaction.TransactionLines[i].CategoryId, 
            new SelectList(x.Transaction.TransactionLines[i].References.Categories, "Value", "Text", x.Transaction.TransactionLines[i].CategoryId), "Select one", 
            new { @onchange = "populateSubCategory(0)", @class = "cmbCategory form-control" }) 
     </div> 
    </div> 
} 
+0

谢谢。我现在就这样做了....任何想法,如果我还可以更改'label for =“中的名称?需要将计数器号码附加到名称上,所以,“cmbCategory1 ... 2,... 3 ... etc – Craig

+0

@Craig你可以试试吗?'' –