问题
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
回答1:
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.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/17545828/extend-hiddenfor-templates-in-asp-net-mvc