Home > Mobile >  C# MVC How to initialize ViewDataDictionary with both TemplateInfo and KeyValuePairs
C# MVC How to initialize ViewDataDictionary with both TemplateInfo and KeyValuePairs

Time:09-18

I can initialize a ViewDataDictionary with Keys and Values or a property called TemplateInfo but not both.

Either this works

Html.RenderPartial("~/Views/_myPartial1.cshtml", Model, new ViewDataDictionary
{
    TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "myForm_" }
});

or this works

Html.RenderPartial("~/Views/_myPartial1.cshtml", Model, new ViewDataDictionary
{
    { "ButtonText", "Hello!" }
});

But not both

Html.RenderPartial("~/Views/_myPartial1.cshtml", Model, new ViewDataDictionary
{
    TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "myForm_" },
    { "ButtonText", "Hello!" }
});

I get an error--- "Invalid initializer member declarator"

I'm guessing this could apply to other types of Dictionary / KeyValuePair sub- classes, so maybe the more general form of this question would be...

"Is there a short cut way of initializing a dictionary's subclass with its members and additional properties ?
If not then any easy alternatives ?"

We're still on .Net 4.5 at work so I may not have access to the latest improvements in C#.

CodePudding user response:

Does this help you?

var dict = new ViewDataDictionary
{
    { "ButtonText", "Hello!" }
};
dict.TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "myForm_" };

Html.RenderPartial("~/Views/_myPartial1.cshtml", Model, dict);
  • Related