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.