Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model prefix when using typed HTML helpers

Tags:

asp.net-mvc

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"?

like image 460
Gopher Avatar asked Mar 29 '10 11:03

Gopher


People also ask

What is strongly typed HTML helpers in MVC?

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.

What is HTML helpers in MVC with example?

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.


2 Answers

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.

like image 85
runesoerensen Avatar answered Nov 13 '22 04:11

runesoerensen


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.

like image 28
Darin Dimitrov Avatar answered Nov 13 '22 05:11

Darin Dimitrov