Search code examples
asp.net-mvcasp.net-core-mvcmvc-editor-templates

pass value from EditorTemplate to its Layout Template only, in mvc 6


is there a way of passing value from the EditorTemplate to its Layout (not the site _Layout, but the template Layout)

in MVC 5 I was having something like this: EditorTemplates/MyStr.cshtml

@{
    Layout = "_FieldLayout.cshtml";
    ViewData.ModelMetadata.AdditionalValues.Add("__idpostfix", "-cde");
}
@Html.CustomHelper("") 

the CustomHelper uses 2 input tags, one for display/edit and other for holding value, both have ids, the display one has -cde postfix and the _FieldLayout.cshtml had this:

@{
    var postfix = ViewData.ModelMetadata.AdditionalValues.ContainsKey("__idpostfix") ? ViewData.ModelMetadata.AdditionalValues["__idpostfix"] : string.Empty;
}
@Html.Label("", new {@for = ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty) + postfix})
... 

now in mvc 6 AdditionalValues is a ReadOnly dictionary, so is there another way of doing this, atm my best bet is to just use a different FieldLayout for when I need the postfix


Solution

  • You can use ViewData to pass data from a child view to its layout page (this is not specific to Editor Templates).

    In EditorTemplates/MyStr.cshtml you can set ViewData["somedata"] = "some value"; and then in _FieldLayout.cshtml you can consume it just as easily.

    The "child" page of a layout runs first, so any code that it runs that has side-effects (such as setting ViewData) will be visible to the layout page.

    Also note that the ViewData for a given page won't leak "back up", so there is no need to reset it after consuming it.