Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get model's field name in custom editor template

I'm building my first custom editor template for a text area control. My code so far is -

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%= Html.TextAreaFor( Model => Model , 2, 30, 
     new { @class = "html", @placeholder = ViewData.ModelMetadata.Watermark }) %>

It's not much so far, but it does work. But we need to add a character counter field to show remaining number of characters that the user can type in. I know how to do all the JavaScript to make this work.

So to keep naming system same, I'm going to add a control named ".charCounter" to display number of remaining characters left. My problem is that I cannot figure out the correct syntax to be able to retrieve the field name for the model.

The final version will look something like (JavaScript omitted) -

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%= Html.TextAreaFor( Model => Model , 2, 30, 
     new { @class = "html", @placeholder = ViewData.ModelMetadata.Watermark }) %>
<span class="xxx">Remaining characters - 
     <input readonly type="text" name="<fieldName>.charCounter" />
</span>
like image 891
photo_tom Avatar asked Jul 07 '11 18:07

photo_tom


4 Answers

You could use ViewData.TemplateInfo.HtmlFieldPrefix, like this:

<input 
    readonly="readonly" 
    type="text" 
    name="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>.charCounter" 
/>
like image 77
Darin Dimitrov Avatar answered Nov 19 '22 14:11

Darin Dimitrov


I ran into an issue where the PropertyName wasn't returning the Model prefix eg Contact.FirstName. I was able to have it return the HTML field Id using this:

@ViewData.TemplateInfo.GetFullHtmlFieldId("")

Returns: Contact_FirstName

Respectively you can return the field name using:

@ViewData.TemplateInfo.GetFullHtmlFieldName("")

Returns:

Contact.FirstName

like image 29
Sir CodesALot Avatar answered Nov 19 '22 15:11

Sir CodesALot


ViewData.ModelMetadata.PropertyName works nicely in MVC3.

In razor:

<input readonly="readonly" type="text" name="@ViewData.ModelMetadata.PropertyName">
like image 37
James Hulse Avatar answered Nov 19 '22 15:11

James Hulse


Getting just the model name/Id (e.g BirthDate):

ViewData.ModelMetadata.PropertyName;

Getting the model name with prefixes for complex objects (e.g Identity.Person.BirthDate):

@Html.NameFor(m => Model);

or

ViewData.TemplateInfo.HtmlFieldPrefix;

Getting the model Id with prefixes for complex objects (e.g Identity_Person_BirthDate):

@Html.IdFor(m => Model)

or

@Html.IdForModel()
like image 35
n.y Avatar answered Nov 19 '22 13:11

n.y