Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend HiddenFor Templates in ASP.NET MVC

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

like image 996
float Avatar asked Jul 09 '13 10:07

float


3 Answers

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.

like image 87
Andrei Avatar answered Oct 20 '22 00:10

Andrei


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

like image 36
Ivan Manzhos Avatar answered Oct 20 '22 00:10

Ivan Manzhos


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.

like image 34
RubberDuck Avatar answered Oct 20 '22 01:10

RubberDuck