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

sri*_*tha 5 dictionary asp.net-mvc-4

我有一个像下面的ViewModel,

public class EnrollPlanPriceLevelViewModel
{
    public EnrollPlanPriceLevel EnrollPlanPriceLevels { get; set; }        
    public Dictionary<PriceLevel,decimal> Prices { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

我的视图中的代码,但我无法创建查看价格.请帮帮我一个人!

 @{
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>
}
                }
Run Code Online (Sandbox Code Playgroud)

我想在Controller中调用Dictionary对象值如何?

sri*_*tha 8

ViewModel:

public class EnrollPlanPriceLevelViewModel
{

    public EnrollPlanPriceLevel EnrollPlanPriceLevels { get; set; }
    public Dictionary<string,decimal> Prices { get; set; }      
}
Run Code Online (Sandbox Code Playgroud)

我的Controller的Get方法应该像这样初始化'Key'和Values.这样您就可以在View中遍历每个KeyValue对.

控制器的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);
    }
Run Code Online (Sandbox Code Playgroud)

像这样使用Dictionary查看:

 <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>
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述