Question

I'm having some problems with parsing in some data to a PartialView. When parsing in a Dictionary the properties Values and Keys is set in the ViewData ... How can I merge the Dictionary with the ViewData ... so I can access my Dictionary items with the Keys like this:

ViewData["key"] as IList<T>;

Instead of

ViewData["Values] <- Which is a List that Contains my list.

I'm going to use it like this ... just dont want anonymous/magic string names.

<%: Html.EditorFor(x => x.GroupId, "SimpleSelectList", new { Selected = 10}) %>

I'm hoping to do something like this. <%: Html.EditorFor(x => x.GroupId, "SimpleSelectList", Html.AddViewData(Model.List)) %>

With this extension method:

public static IDictionary AddViewData<T>(this HtmlHelper helper, T item)
{
    var dictionary = new Dictionary<string, object>();
    dictionary.Add(typeof(T).Name, item);
    return dictionary;
}

Then I will always know what the SimpleSelectList template should look for ... and dont have to depends on yet again another magic string ...

Or how do people do this? Just trying to get into the code base and how people do this kind of thing ...

Was it helpful?

Solution

Personally I wouldn't use ViewData atall in this context.

It's a lot cleaner and clearer to have a view model that impliments your dictionary as a property. You can then pass this view model to your view, and to your partial view...or just part of the view model to your partial view (depending on what data you need).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top