在View頁面使用Razor語法的Html.TextBoxFor時
檢視原始法發現Html的Tag的name及id屬性長出奇怪的前綴字CS$<>8__locals或CS___8__locals
模擬重現狀況
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var viewModel = new List<TestModel>() {
new TestModel{ Id =1, TestTitle="Hello", TestContent = "Good morning"},
new TestModel{ Id =2, TestTitle="Hi", TestContent = "Happy new year"},
new TestModel{ Id =3, TestTitle="Hey", TestContent = "How are you"}
};
return View(viewModel);
}
}
Model:
public class TestModel
{
public int Id { get; set; }
public string TestTitle { get; set; }
public string TestContent { get; set; }
}
View:
@using CS8.Models
@model List<TestModel>
@{
ViewBag.Title = "Home Page";
var input = new List<TestModel>();
}
<ul>
@for (int i = 0; i < Model.Count(); i++)
{
input.Add(new TestModel {
Id = Model[i].Id ,
TestTitle = Model[i].TestTitle,
TestContent = Model[i].TestContent
}
);
<li>
<span>ID | @Html.TextBoxFor(x => input[i].Id)</span>
<span>TestTitle | @Html.TextBoxFor(x => input[i].TestTitle)</span>
<span>TestContent | @Html.TextBoxFor(x => input[i].TestContent)</span>
</li>
}
</ul>
會發現HTML的Element上多了一些非預期的前綴字
解決方式
@using CS8.Models
@model List<TestModel>
@{
ViewBag.Title = "Home Page";
var input = new List<TestModel>();
}
<ul>
@{
//在for迴圈外層另外定義一個index變數不使用for迴圈的i變數去取出input的值
int index = 0;
for (int i = 0; i < Model.Count(); i++)
{
input.Add(new TestModel
{
Id = Model[i].Id,
TestTitle = Model[i].TestTitle,
TestContent = Model[i].TestContent
}
);
<li>
<span>ID | @Html.TextBoxFor(x => input[index].Id)</span>
<span>TestTitle | @Html.TextBoxFor(x => input[index].TestTitle)</span>
<span>TestContent | @Html.TextBoxFor(x => input[index].TestContent)</span>
</li>
index++;
}
}
</ul>
輸出結果
參考:
https://stackoverflow.com/questions/34618711/weird-input-name-generated-by-checkboxfor