我如何在MVC4 ViewModel,Controller,View中使用Dictionary?

时间:2013-12-03 05:20:56

标签: asp.net-mvc-4 dictionary

我有一个像下面的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对象值如何?

2 个答案:

答案 0 :(得分:8)

ViewModel:

public class EnrollPlanPriceLevelViewModel
{

    public EnrollPlanPriceLevel EnrollPlanPriceLevels { get; set; }
    public Dictionary<string,decimal> Prices { get; set; }      
}

My Controller的Get方法应该像这样初始化'Key'和Values。这样你就可以在View中为每个KeyValue对循环。

Controller的GET方法:

 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>

Controller的POST方法:显示字典的值

enter image description here

答案 1 :(得分:0)

prices是一个词典项目(例如KeyValuePair<PriceLevel, decimal>)。

因此,您必须分别绑定对中的每个属性:KeyValue