Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

c# - htmlFieldPrefix breaks names outside partial view

I have a view, which contains this snippet:

@{Html.RenderPartial("~/Features/MainPage/_MyPartialView.cshtml", Model.PartialViewViewModel); }
@Html.HiddenFor(x => x.Model.SomeProperty)

And my partial view starts with

@model PartialViewViewModel
@{
  Html.ViewData.TemplateInfo.HtmlFieldPrefix = "PartialViewViewModel";
}

The issue is, that HiddenProperty's name from the view is generated using partial view's prefix too. It's "PartialViewViewModel.SomeProperty" instead of "SomeProperty". Switching hiddenfor and partial view in places fixes the problem (name becomes "SomeProperty"). Is there a way to isolate HtmlFieldPrefix just for the partial view?

question from:https://stackoverflow.com/questions/65921408/htmlfieldprefix-breaks-names-outside-partial-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try to add

@{
    Html.ViewData.TemplateInfo.HtmlFieldPrefix = "";
}

into the view you contains the Partial view.

Here is a demo:

Models:

public class ParentModel
    {
        public PartialViewViewModel PartialViewViewModel { get; set; }
        public string SomeProperty { get; set; }
    }
public class PartialViewViewModel
    {
        public int Id { get; set; }
    }

_MyPartialView.cshtml:

@{
    Html.ViewData.TemplateInfo.HtmlFieldPrefix = "PartialViewViewModel";
}
@Html.TextBoxFor(m=>m.Id)

View Containing _MyPartialView:

@{
    Html.ViewData.TemplateInfo.HtmlFieldPrefix = "";
}
@model ParentModel
@{Html.RenderPartial("_MyPartialView.cshtml", Model.PartialViewViewModel); }
@Html.HiddenFor(x => x.SomeProperty)

result: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...