sridharnetha
sridharnetha

Reputation: 2248

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?

Upvotes: 5

Views: 10502

Answers (2)

sridharnetha
sridharnetha

Reputation: 2248

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

Upvotes: 8

Sam Axe
Sam Axe

Reputation: 33738

prices is a Dictionary item (e.g. KeyValuePair<PriceLevel, decimal>).

So you must bind each property of the pair: Key and Value separately.

Upvotes: 0

Related Questions