MVC4 ViewData.TemplateInfo.HtmlFieldPrefix generates an extra dot

你。 提交于 2019-12-05 04:33:57

There is no need set the HtmlFieldPrefix value. MVC will correctly name the elements if you use an EditorTemplate based on the property type (and without the template name).

Assumed models

public class ListElement
{
  public string Value { get; set; }
  ....
}

public class MyViewModel
{
  public IEnumerable<ListElement> MyItems { get; set; }
  ....
}

Editor template (ListElement.cshtml)

@model YourAssembly.ListElement
@Html.TextBoxFor(m => m.Value)

Main view

@model YourAssembly.MyViewModel
...
@Html.EditorFor(m => m.MyItems) // note do not specify the template name

This will render

<input type="text" name="MyItems[0].Value" ...>
<input type="text" name="MyItems[1].Value" ...>
....

If you want to do this using a partial, you just can pass the whole model to the partial

MyPartial.cshtml

@model @model YourAssembly.MyViewModel
@Html.EditorFor(m => m.MyItems)

and in the main view

@Html.Partial("MyPartial")

or create an extension method

public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
  Expression<Func<TModel, TProperty>> expression, string partialViewName)
  {
    string name = ExpressionHelper.GetExpressionText(expression);
    object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
    var viewData = new ViewDataDictionary(helper.ViewData)
    {
      TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = name }
    };
    return helper.Partial(partialViewName, model, viewData);
  }
}

and use as

@Html.PartialFor(m => m.MyItems, "MyPartial")

and in the partial

@model IEnumerable<YourAssembly.ListElement>
@Html.EditorFor(m => m)
  1. Call your partial this way:
@Html.Partial("_SeatTypePrices", Model.SeatTypePrices, new ViewDataDictionary
{
    TemplateInfo = new TemplateInfo() {HtmlFieldPrefix = nameof(Model.SeatTypePrices)}
})
  1. Partial view:
@model List
@Html.EditorForModel()
  1. Editor template implementation:

    @using Cinema.Web.Helpers
    @model Cinema.DataAccess.SectorTypePrice
    @Html.TextBoxFor(x => Model.Price)
    

This way your partial view will contain list of items with prefixes. And then call EditorForModel() from your EditorTemplates folder.

I found that I can change the value of HtmlFeildPrefix in my template.

So what I did to solve my problem was just to assign the correct value to HtmlFeildPrefix in the template directly rather than in the page which calls the template.

I hope it helps.

If I want to pass the HtmlFieldPrefix I use the following construct:

<div id="_indexmeetpunttoewijzingen">
    @Html.EditorFor(model => model.MyItems, new ViewDataDictionary()
    {
        TemplateInfo = new TemplateInfo()
        {
            HtmlFieldPrefix = "MyItems"
        }
    })
</div>                       
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!