解决 我必须填写控制器中的集合,然后使用下面的评论中解释的方法。谢谢大家的帮助:))
我有一个简单的网站,我想在这里向所有商店添加特定食品的价格。 我选择项目,如苹果,然后列出我可以添加价格的所有商店。
模型有一个集合(List)。在视图中,我浏览商店,创建价格的新实例,在文本框中输入价格并将其添加到集合中。
问题是,控件中的集合是空的。
有什么建议吗?谢谢!
编辑:商店集合只是为了提供ShopID。价格收集是一个,它来到视图空,我需要填充它,以处理控制器中的数据。
型号:
public class PriceMultiple
{
private List<Price> _NewPrices;
public List<Price> NewPrices
{
get
{
if (_NewPrices == null)
_NewPrices = new List<Price>();
return _NewPrices;
}
set { _NewPrices = value; }
}
...
}
查看:
...
@foreach (Shop shop in ViewBag.ShopsToLoad)
{
Price price = new Price();
price.ItemID = Model.ItemID.Value;
price.ShopID = shop.ShopID;
@shop.Name
<div class="form-group">
@Html.Label("price.Value", "Cena")
<div class="col-md-10">
@Html.Editor("price.Value")
</div>
</div>
Model.NewPrices.Add(price);
}
...
答案 0 :(得分:1)
您的问题源于您的呈现标记不符合模型绑定的ASP.Net Wire Format:
简而言之,您需要确保在处理集合时,表单控件具有非常具体的名称。来自参考:
我们在属性中读取的方式是查找parameterName [index] .PropertyName。索引必须从零开始且不间断。
你没有提供你的View键入的模型,所以我猜这里,但你的控件需要渲染出类似的东西:
<input type="text" name="shop[0].price[0]" />
<input type="text" name="shop[0].price[1]" />
<input type="text" name="shop[1].price[0]" />
<input type="text" name="shop[1].price[1]" />
Razor中的股票帮助者不会为你构建这些,你将不得不构建一个自定义编辑器,或者只是编写输入 - 记住,MVC不会妨碍你!
@for(var i = 0; i < ViewBag.ShopsToLoad.length; i++){
@for(var j = 0; j < ViewBag.ShopsToLoad[i].Prices.length; j++){
<input type="text" name="shop[@i].price[@j]" />
}
}
答案 1 :(得分:0)
从过去使用基本表单将集合发布到控制器的经验给我带来了麻烦。
我建议您使用Javascript MVVC框架收集值,然后发布到您的控制器。
我使用了敲击和角度来做到这一点。如果您对此感兴趣,可以稍微简单一些。
答案 2 :(得分:0)
如果你在控制器和模型中做了更多工作并且给视图提供了一个强类型模型来处理,你可能会让你的生活变得更轻松。
以下是我的头脑,所以不要只剪切并粘贴它,并期望它能够正常工作。
模型
public class PriceByShop
{
public int ShopId { get; set; }
public string ShopName { get; set; }
public decimal Price { get; set; }
}
控制器
public ActionResult Prices()
{
var pricesByShop = new List<PriceByShop>();
// some code here to add an object to the list for each shop
// initialize Price with existing price or set to 0...
return View( pricesByShop );
}
查看
@model List<PriceByShop>
@for( int i = 0; i < Model.Count; i++ )
{
@Model[i].ShopName
<div class="form-group">
@Html.LabelFor( model => model[i].Price, "Cena" )
<div class="col-md-10">
@Html.EditorFor( model => model[i].Price )
</div>
</div>
}