使用Html.EditorFor()爲文本框加上maxlength,placeholder等屬性

當想經過Html.EditorFor()給文本框加上maxlength,placeholder等屬性的時候,發現Html.EditorFor()沒有提供可直接加上這些屬性的重載方法,如何作到呢?css


□ 思路html

一、Html.EditorFor()有一個重載方法以下:spa

4

 

也許,能夠把須要給文本框加上的屬性(maxlength, placeholder,etc),封裝成一個匿名對象,做爲路由數據傳遞給一個模版。code

 

二、Html.TextBox()正好有一個重載能夠把路由數據做爲它的htmlAttributes參數:orm

5

 

首先,在Views/Shared/下建立EditorTemplates文件夾,並在EditorTemplates文件夾下建立部分視圖string.cshtmlhtm

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

而後,建立一個View Model:對象

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

接着,控制器方法把強類型model傳遞到對應的視圖中:blog

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

 

最後,在強類型視圖頁,把須要給文本框加上的屬性封裝成匿名對象,做爲路由數據傳遞給模版頁。路由

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

 

□ 結果rem

因爲有了placeholder,顯示水印:

1


因爲有了maxlength,最多隻能輸入5個字符:

2


在html代碼中的input有了maxlength和placeholder屬性:

3


□ 總結

Html.EditorFor()自己沒有給input附加上屬性的重載方法,只好把須要給input附加上的屬性封裝成匿名對象,做爲路由數據交給模版視圖頁,在模版視圖頁Html.TextBox()把接收到的路由數據做爲它的屬性參數,最終顯示出來。

相關文章
相關標籤/搜索