10

The following generates an input element for a model field using a typed helper:

Html.HiddenFor(m => m.FieldName)

The generated field name is FieldName. How do I add a prefix to the name so that it will render as name="prefix.FieldName"?

2 Answers 2

17

You can set the prefix for the HtmlHelper with

htmlHelper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "foo";

So if you set Html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "Foo" before Html.HiddenFor(m => m.FormId) the resulting field name would become 'Foo.FormId'

I'd recommend writing an extension method for the HtmlHelper rather than handling this logic in the view. You might then want to use the modeltype's name as a prefix.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't. You could use editor templates instead. Brad Wilson has a series of blog posts describing them. Scott Gu also covers them in this post.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.