ASP.NET MVC 字典<string,string> 在视图中输出

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

控制器/C#:

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

查看/HTML:

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

但在结果中,第一个输入的占位符只显示 "Simon",最终 HTML:

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

您在视图中缺少围绕变量的引号:

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

用引号括起来的名称和占位符

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