Use Html. EditorFor () to add attributes such as maxlength and placeholder to the text box.

Source: Internet
Author: User

When we want to add maxlength and placeholder attributes to the text box through Html. EditorFor (), we find that Html. EditorFor () does not provide a method to directly add these attributes. How can we do this?


□Ideas

1. Html. EditorFor () has an overload method as follows:

String

 
<span>
    @Html.TextBox("", @ViewData.TemplateInfo.FormattedModelValue, @ViewData) 
</span>   

Then, create a View Model:

namespace MvcApplication1.Models
{
    public class Sample
    {
        public string Name { get; set; }
    }
}

Then, the Controller Method passes the strongly typed model to the corresponding view:

using System.Web.Mvc;
using MvcApplication1.Models;
 
namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Sample());
        }
 
    }
}

 

Finally, on the strong-type view page, encapsulate the attributes that need to be added to the text box into anonymous objects and pass them as routing data to the template page.

@model MvcApplication1.Models.Sample
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
@ Html. EditorFor (s => s. Name, "string", new {maxlength = 5, placeholder = "username "})

 

□Result

With placeholder, the watermark is displayed:


With maxlength, a maximum of five characters can be entered:


The input in html code has the maxlength and placeholder attributes:


□Summary

Html. editorFor () itself does not include an overload method for attributes attached to the input, so you have to encapsulate the attributes to be appended to the input into anonymous objects and send them as routing data to the template view page, in the template view page, Html. textBox () uses the received route data as its attribute parameter and displays it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.