简体   繁体   English

使用MVC 3(Razor)的ASP.NET部分视图和隐藏变量

[英]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? 有没有办法让Html.HiddenFor(或等效的)将类/结构名称放在前面?

Two options: 两种选择:

  1. Use Html.EditorFor(..) instead of straight partial views. 使用Html.EditorFor(..)而不是直接部分视图。 EditorFor takes into account the prefix/heirachy used to reach the property, or, EditorFor考虑到用于到达酒店的前缀/ heirachy,或者,

  2. manipulate T emplateInfo.HtmlFieldPrefix before rendering the child partial, which will cause each field rendered by the child to be prefixed automatically. 在渲染子部分之前操纵T emplateInfo.HtmlFieldPrefix ,这将导致子项呈现的每个字段自动加上前缀。

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). 如果你选择选项(2),考虑声明一个帮助器,它将包装HtmlFieldPrefix操作以防止你忘记重置它(我在ChildPrefixScope某个地方从我的某个地方撕下了ChildPrefixScope的代码)。

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;
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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