John
John

Reputation: 3

ASP.NET MVC Dictionary<string,string> output in view

Controller / C#:

public Action GetData()
{
    ViewBag.InputData = new Dictionary<string, string>
    {
         ["Name"] = "Simon Lin",
         ["Age"] = "18"
    };
    return View();
}

View / HTML:

@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
     <input type="text" [email protected] value="" [email protected] />
}

But in the result, first input's placeholder only show "Simon", Final HTML:

<input type="text" name="Name" value="" placeholder="Simon" Lin="">

Upvotes: 0

Views: 1616

Answers (2)

Abdul
Abdul

Reputation: 2120

Enclosed Name and Placeholder in quotes

@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
   <input type="text" name="@keyValuePair.Key" value="" 
 placeholder="@keyValuePair.Value"/>
}

Upvotes: 0

Raidri
Raidri

Reputation: 17550

You are missing quotes around the variables in your view:

<input type="text" name="@keyValuePair.Key" value="" placeholder="@keyValuePair.Value" />
                        ^                 ^                      ^                   ^

Upvotes: 2

Related Questions