我正在尝试获取正确的输入名称,以便我的 View 模型上的对象集合可以被绑定(bind)。
@{ViewData.TemplateInfo.HtmlFieldPrefix = listName;}
@Html.EditorFor(m => m, "DoubleTemplate", new {
Name = listName,
Index = i,
Switcher = (YearOfProgram >= i +1)
})
正如您在此处看到的,我传入“listName”作为模板的前缀,listName =“MyItems”的值。这是我的模板:
@model Web.Models.ListElement
@if (ViewData["Switcher"] != null)
{
var IsVisible = (bool)ViewData["Switcher"];
var index = (int)ViewData["Index"];
var thisName = (string)ViewData["Name"] + "[" + index + "].Value";
var thisId = (string)ViewData["Name"] + "_" + index + "__Value";
if (IsVisible)
{
@*<input type="text" value="@Model.Value" name="@thisName" id ="@thisId" class="cell@(index + 1)"/>*@
@Html.TextBoxFor(m => m.Value, new { @class ="cell" + (index + 1)})
@Html.ValidationMessageFor(m => m.Value)
}
}
但是我发现生成的名字变成了这样: MyItems.[0].Value 它有一个额外的点。我怎样才能摆脱它?
顺便说一句,我尝试在模板中手动指定名称,发现该名称被 Html 帮助程序覆盖。
更新
我必须手动设置 HtmlFieldPrefix 的原因是当 MyItems 从主视图传递到部分 View 时,属性名称(MyItems 是对象列表)会丢失。当局部 View 调用我的模板并传入 MyItems 中的一个对象时,模板本身无法确定 MyItems 的名称,因为它自上次“传入”以来已经丢失。
所以这就是为什么我必须手动设置 html 字段前缀名称。我什至尝试使用类似于反射的东西(但不是连任,我忘记了名字)来检查传入对象的名称,发现它返回了“模型”。
更新 2
我尝试了 Stephen 的方法,但找不到 html 助手 PartialFor()。
我什至尝试在我的主视图中使用它:
Html.Partial(Model, "_MyPartialView");
在部分 View 中:@model MvcApplication1.Models.MyModel
<h2>My Partial View</h2>
@Html.EditorFor(m => m.MyProperty)
这是我的模板:@model MvcApplication1.Models.ListElement
@Html.TextBoxFor(m => m.Value)
这是我的模型: public class MyModel
{
private List<ListElement> myProperty;
public List<ListElement> MyProperty
{
get
{
if (myProperty == null)
{
this.myProperty = new List<ListElement>() { new ListElement() { Value = 12 }, new ListElement() { Value = 13 }, new ListElement() { Value = 14 }, new ListElement() { Value = 15 }, };
}
return this.myProperty;
}
set
{
this.myProperty = value;
}
}
}
public class ListElement
{
[Range(0, 999)]
public double Value { get; set; }
}
这是我的 Controller :public ActionResult MyAction()
{
return View(new MyModel());
}
它只为我生成原始文本(“12131415”),而不是用 12 13 14 15 填充的想要的文本框。但是,如果我指定了模板名称,它会抛出一个异常:
The template view expecting ListElement, and cannot convert
List<ListElement> into ListElement.
最佳答案
@Html.Partial("_SeatTypePrices", Model.SeatTypePrices, new ViewDataDictionary
{
TemplateInfo = new TemplateInfo() {HtmlFieldPrefix = nameof(Model.SeatTypePrices)}
})
@model List
@Html.EditorForModel()
@using Cinema.Web.Helpers
@model Cinema.DataAccess.SectorTypePrice
@Html.TextBoxFor(x => Model.Price)
这样,您的部分 View 将包含带有前缀的项目列表。
然后调用
EditorForModel()
来自您的EditorTemplates
文件夹。
关于asp.net-mvc-4 - MVC4 ViewData.TemplateInfo.HtmlFieldPrefix 生成一个额外的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719947/