Domanda

I am using ASP.Net MVC 3 and Razor

How do i create a custom HTML helper for the below strucure. This should be bound to model property also i should pass parameteres to label, span, input.

Any code sample for this below mark up?

    <label class="field">
       <span class="td">User Name</span>
       <input type="text" name="UserName" class="highlight">
    </label>

Update:

I tried below but display text for not showing the text i used in model

   <label for="login_field">
      <span class="td"> @Html.DisplayTextFor(m=>m.UserName)</span>
        @Html.TextBoxFor(model => model.UserName, 
           new { style = "width:21em", @class = "text" })

   </label>

My View Model is below and use Resource file to fetch text

 using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Web;

namespace MVC.ViewModel
{
    public class LoginViewModel
    { 
        [Required]
        [Display(Name = "UserName", ResourceType = typeof(Resources.Global))]
        public string UserName { get; set; }

    }
}
È stato utile?

Soluzione

it is better to create a function that calls a helper. this should give you a hint how to implement yours

@functions
{
public HelperResult CustomFormTextboxFor<TModel,TProperty>(HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
    var textBox= html.TextBoxFor(expression, new {@class = "highlight"});
    var modelsMetaDatas = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    string displayValue = modelsMetaDatas.DisplayName ?? (metaData.PropertyName ??   ExpressionHelper.GetExpressionText(expression));
    return RenderCustomControl(textBox, displayValue);
}
}

@helper RenderCustomFormTextbox(MvcHtmlString input, string labeltext)
{
   <label class="field">
       <span class="td">@labeltext</span>
       @input
    </label> 
}

The call of the function in you view will look something like this.

@CustomFormTextboxFor(Html, model => model.FirstName)

Hope this helps

Altri suggerimenti

Replace this

@Html.DisplayTextFor(m=>m.UserName)

With

@Html.LabelFor(m=>m.UserName)

For more detail about the DisplayTextFor follow the below link

What's the point of Html.DisplayTextFor()?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top