Controller / 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 />
}
但是在结果中,第一个输入的占位符只显示&#34; Simon&#34;,最终HTML:
<input type="text" name="Name" value="" placeholder="Simon" Lin="">
答案 0 :(得分:2)
您在视图中的变量周围缺少引号:
<input type="text" name="@keyValuePair.Key" value="" placeholder="@keyValuePair.Value" />
^ ^ ^ ^
答案 1 :(得分:0)
用引号括起名称和占位符
@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
<input type="text" name="@keyValuePair.Key" value=""
placeholder="@keyValuePair.Value"/>
}