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

 双手描绘我们的幸福_688 发布于 2023-02-13 12:12

我有一个像下面的ViewModel,

public class EnrollPlanPriceLevelViewModel
{
    public EnrollPlanPriceLevel EnrollPlanPriceLevels { get; set; }        
    public Dictionary Prices { get; set; }

}

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

 @{
int i = 0;
foreach (FCA.Model.PriceLevel p in ViewBag.PriceLevelID)
{
    i = i + 1;
                    
@Html.TextBoxFor(model => model.Prices[p], new { @placeholder = "Price" })
} }

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

1 个回答
  • ViewModel:

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

    我的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);
        }
    

    像这样使用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>
    

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

    在此输入图像描述

    2023-02-13 12:16 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有