Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use Dictionary in MVC4 ViewModel,Controller, View?

I have a ViewModel like below,

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

}

Code in my View, but I am unable to create View for Prices. Please help me someone!

 @{
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>
}
                }

I want to call Dictionary object values in Controller how?

like image 627
sridharnetha Avatar asked Dec 03 '13 05:12

sridharnetha


1 Answers

ViewModel :

public class EnrollPlanPriceLevelViewModel
{

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

My Controller's Get method should intitialize 'Key' and Values like this. so that you can loop through in View for each KeyValue pair.

Controller's GET method:

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

View using Dictionary like this:

 <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's POST method: presenting dictionary's values

enter image description here

like image 70
sridharnetha Avatar answered Nov 15 '22 09:11

sridharnetha