我比赛迟到了。我正在与 EditorFor 斗争。
不是使用模板在文本框中显示实体的名称,而是将名称写入屏幕。它似乎正在写入对象的第一个属性,就像在我的真实项目中正在写入 guid 一样。
如何在指定模板时使用编辑器?
家庭 Controller
public ActionResult Index()
{
HomeModel homeModel = new HomeModel();
homeModel.RoomModels = new List<RoomModel>();
homeModel.RoomModels.Add(new RoomModel() { RoomName = "Room-1" });
homeModel.RoomModels.Add(new RoomModel() { RoomName = "Room-2" });
homeModel.RoomModels.Add(new RoomModel() { RoomName = "Room-3" });
return View(homeModel);
}
家居模型
public class HomeModel
{
public List<RoomModel> RoomModels { get; set; }
}
房间模型
public class RoomModel
{
public string RoomName { get; set; }
}
/Views/Home/Index.cshtml
@model MVC.Temp.Models.Home.HomeModel
<h1>Home</h1>
<div id="RoomModels">
@Html.EditorFor(m => m.RoomModels, "_RoomModelEditor")
</div>
/Views/Home/_RoomModelEditor.cshtml
@model MVC.Temp.Models.Home.RoomModel
@Html.TextBoxFor(x => x.RoomName)
当前输出:
最佳答案
您需要将编辑器模板放在名为 EditorTemplates 的目录中。所以正确的路径应该是这样的:
/Views/Home/EditorTemplates/_RoomModelEditor.cshtml
来自documentation :
If a template whose name matches the templateName parameter is found in the controller's EditorTemplates folder, that template is used to render the expression. If a template is not found in the controller's EditorTemplates folder, the Views\Shared\EditorTemplates folder is searched for a template that matches the name of the templateName parameter. If no template is found, the default template is used.
关于asp.net-mvc-3 - MVC 3 EditorFor 指定模板时的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12789481/