2011年9月9日 星期五

Html attributes for EditorFor() in ASP.NET MVC 3(use Razor)

最近剛使用ASP.NET的新的view engine:Razor
專案中想讓view的某個欄位是disable的
但是原本用Visual Studio幫你產生出來時,view中的code對於欄位會產生如下:

@Html.EditorFor(model => model.EmployeeNo)


想要讓該欄位disable,後來找了一下資料,試成這樣:


@Html.EditorFor(model => model.EmployeeNo,
new { disabled = "disabled", readonly = "readonly" }

)

結果還是不行,產生出來的html語法還是沒變
後來才知道,如果要用EditorFor,是要搭配metadata的
可參考
 Adding html attributes support for Templates - ASP.Net MVC 2.0 Beta

或者是直接用TextFor也可以

 @Html.TextBoxFor(model => model.EmployeeNo, new { disabled = "disabled" })

(註:當將TextBoxFor的欄位設定成disabled,若有存檔的功能時
傳送到Controller的Action,則該欄位是會變成null的)

不過上面講到的都是MVC 2的用法
至於MVC 3有沒有改進,這我還沒找到
等找到再來補充

沒有留言:

張貼留言