我有一个像下面的ViewModel,
public class EnrollPlanPriceLevelViewModel
{
public EnrollPlanPriceLevel EnrollPlanPriceLevels { get; set; }
public Dictionary<PriceLevel,decimal> Prices { get; set; }
}
我的视图中的代码,但我无法创建View for Price。请帮帮我一个人!
@{
int i = 0;
foreach (FCA.Model.PriceLevel p in ViewBag.PriceLevelID)
{
i = i + 1;
<div class="span4">
@Html.TextBoxFor(model => model.Prices[p], new { @placeholder = "Price" })
</div>
}
}
我想在Controller中调用Dictionary对象值如何?
答案 0 :(得分:8)
public class EnrollPlanPriceLevelViewModel
{
public EnrollPlanPriceLevel EnrollPlanPriceLevels { get; set; }
public Dictionary<string,decimal> Prices { get; set; }
}
My Controller的Get方法应该像这样初始化'Key'和Values。这样你就可以在View中为每个KeyValue对循环。
public ActionResult Create()
{
var model = new EnrollPlanPriceLevelViewModel();
model.Prices = new Dictionary<string, decimal>();
foreach (PriceLevel p in db.PriceLevelRepository.GetAll().ToList())
{
model.Prices.Add(p.PriceLevelID.ToString(), 0);
}
return View(model);
}
<div class="span12">
@{
foreach (var kvpair in Model.Prices)
{
<div class="span4">
@Html.TextBoxFor(model => model.Prices[kvpair.Key], new { @placeholder = "Price" })
@Html.ValidationMessageFor(model => model.Prices[kvpair.Key])
</div>
}
}
</div>
答案 1 :(得分:0)
prices
是一个词典项目(例如KeyValuePair<PriceLevel, decimal>
)。
因此,您必须分别绑定对中的每个属性:Key
和Value
。