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"
?
The Strongly-Typed HTML helper (i.e., NumericTextBox) takes lambda as a parameter that tells the helper, which element of the model to be used in the typed view. The Strongly typed views are used for rendering specific types of model objects, instead of using the general ViewData structure.
In MVC, HTML Helper can be considered as a method that returns you a string. This string can describe the specific type of detail of your requirement. Example: We can utilize the HTML Helpers to perform standard HTML tags, for example HTML<input>, and any <img> tags.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With