Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

<input 
    readonly="readonly" 
    type="text" 
    name="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>.charCounter" 
/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...