Extend HiddenFor Templates in ASP.NET MVC
Asked Answered
H

3

5

I thought Html.HiddenFor could use Templates like Html.DisplayFor or Html.EditorFor. Unfortunately the method doesn't accept a TemplateName like the others.

I know, the workaround would be to use a DisplayFor/EditorFor Template which has HiddenFors. But I would like to find out how to extend the Html.HiddenFor method. Anyone?

Regards

Hoshi answered 9/7, 2013 at 10:25 Comment(0)
E
5

Seems like you are mislead by wrong analogy. HiddenFor corresponds exactly to the <input type="hidden"/> tag. Just like TextBoxFor, CheckBoxFor etc. These methods are not designed to use templates. DisplayFor/EditorFor on the other side are specially created to be used with templates defined in the project. Thus what you are asking for is not possible out-of-the-box.

However you can always define your own overload for HiddenFor with whatever set of parameters and whatever logic you might require.

Euryale answered 9/7, 2013 at 10:31 Comment(0)
I
1

There is an overload which accept additional parameter - htmlAttributes. And you can use it for add some attributes to the result tag.

Also the second way is to create razor partial view in one of the folders

~/Areas/AreaName/Views/ControllerName/DisplayTemplates/TemplateName.cshtml
~/Areas/AreaName/Views/Shared/DisplayTemplates/TemplateName.cshtml
~/Views/ControllerName/DisplayTemplates/TemplateName.cshtml
~/Views/Shared/DisplayTemplates/TemplateName.cshtml

with name HiddenInput.cshtml

Ipomoea answered 9/7, 2013 at 10:31 Comment(0)
G
1

Here's what you do, you create it as an editor template, because as Andre pointed out, HiddenFor is equivalent to the helper methods like TextBoxFor and CheckboxFor.

It's likely that you'll want to have an actual editor too, so place your real editor under ~/Shared/EditorTemplates. We're going to put our "hidden editor" under the controller you wish to use it on.

~/Views/ControllerName/EditorTemplates/ModelName.cshtml

Lets say we have a Person model.

public class Person
{
    public string First { get; set; }
    public string Last { get; set; }
}

We'll create a partial view.

@Model Person

@Html.HiddenFor(p => p.First);
@Html.HiddenFor(p => p.Last);

And then we'll pretend we have a model that contains a Person as a property. From our main view, we call our "hidden editor" like so.

@Model Foo

@Html.EditorFor(f => f.Person)

Easy peasy lemon squeezy. A bit hacky, but it works like a charm.

Girgenti answered 6/2, 2016 at 1:6 Comment(2)
Thanks for this how to, but as I said in my question, I know already that this is a possible workaround :-)Hoshi
This wasn't for you @float. This was to save the next guy like me who googles and finds this Q/A an absurd amount of time.Girgenti

© 2022 - 2024 — McMap. All rights reserved.