简体   繁体   中英

ASP.NET partial views and hidden variables with MVC 3 (Razor)

When generating hidden variables from the Model, only the variable name is used. If a nested class/structure off the model is used, then the class/struct name is used. This helps when posting the form, as it is easier for the system to see the object it is filling.

However, when using partial views, I often pass in parts of the model, which means the hidden fields no longer have the struct/class name in them. This can cause conflict or loss of data when reconstructing the parameters for the post back. Is there any way of getting Html.HiddenFor (or an equivalent) to put the class/struct name on the front?

Two options:

  1. Use Html.EditorFor(..) instead of straight partial views. EditorFor takes into account the prefix/heirachy used to reach the property, or,

  2. manipulate T emplateInfo.HtmlFieldPrefix before rendering the child partial, which will cause each field rendered by the child to be prefixed automatically.

If you go for option (2), consider declaring a helper which will wrap up the HtmlFieldPrefix manipulation to prevent you from forgetting to reset it (I ripped the code for ChildPrefixScope below from somewhere else on SO some time ago).

eg:

static public class MyHtmlHelpers
{
    public static IDisposable BeginChildScope<TModel>(this HtmlHelper<TModel> html, string parentScopeName)
    {
        return new ChildPrefixScope(html.ViewData.TemplateInfo, parentScopeName);
    }

    private class ChildPrefixScope : IDisposable
    {
        private readonly TemplateInfo _templateInfo;
        private readonly string _previousPrefix;

        public ChildPrefixScope(TemplateInfo templateInfo, string collectionItemName)
        {
            this._templateInfo = templateInfo;

            _previousPrefix = templateInfo.HtmlFieldPrefix;
            templateInfo.HtmlFieldPrefix = collectionItemName;
        }

        public void Dispose()
        {
            _templateInfo.HtmlFieldPrefix = _previousPrefix;
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM