How can i use Dictionary in MVC4 ViewModel,Controller, View?
asp.net-mvc-4, dictionary
Solution
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
Problem
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?