2011-06-09 64 views
2

在我的項目中,我要求根據特定條件的某些字段應該可編輯或只讀。在MVC 3中創建自定義用戶界面元素

所以我雖然,這樣做的每一個領域是矯枉過正

@if (Model.CanEdit) 
{ 
    @Html.TextBoxFor(model => Model.Foo, new { width = "100px" }) 
} 
else 
{ 
    @Html.TextBox(model => Model.Foo, new { width = "100px", @readonly = "readonly"}) 
} 

我決定用一個編輯模板,但後來我意識到,寬度不能是固定的,所以我想知道什麼是最好的方式將參數發送到編輯器模板?它也應該處理寬度可能沒有定義的情況,並且根本不使用width屬性。我發現ViewData可能對此有所幫助,但是看起來像這樣的代碼會讓我覺得我做錯了什麼。

@inherits System.Web.Mvc.WebViewPage<string> 
@if (Model.CanEdit) 
{ 
    @if(ViewData["width"] == null) 
    { 
     @Html.TextBox("", Model, new { width = ViewData["width"].ToString() }) 
    } 
    else 
    { 
     @Html.TextBox("", Model) 
    } 
} 
else 
{ 
    @if(ViewData["width"] == null) 
    { 
     @Html.TextBox("", Model, new { width = ViewData["width"].ToString() , @readonly = "readonly"}) 
    } 
    else 
    { 
     @Html.TextBox("", Model, new {@readonly = "readonly"}) 
    } 
} 

我不知道是否有可能創建一個幫手,所以我可以做的方式是這樣的:

@MyTextBoxFor(model => Model.Foo, true) @* true would be or readonly *@ 
@MyTextBoxFor(model => Model.Foo, true, 100) @* 100 would be the width length *@ 

回答

4

kapsi的答案是偉大的,但如果你想使用你的助手在一個強類型來看,這裏的基本語法。這有點草率,但你可以在你認爲合適的時候增加重載。

public static class MyHelpers 
{ 
    public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> expression, 
     bool flagReadonly, 
     int? widthProperty) where TModel : class 
    { 
     MemberExpression memberExpression = expression.Body as MemberExpression; 
     string parameterName = memberExpression.Member.Name; 

     return new MvcHtmlString(
      string.Format("<input id=\"{0}\" name=\"{0}\" {1} {2} />", 
      parameterName, // name and if of parameter 
      flagReadonly ? "readonly=\"readonly\"" : string.Empty, 
      widthProperty.HasValue ? 
       string.Format("width=\"{0}px\"", (int)widthProperty) : 
       string.Empty)); 
    } 
} 

當然,這樣一來,你給予大力鍵入您的視圖元素

@Html.MyTextBoxFor(model => model.Foo, true) 

@Html.MyTextBoxFor(model => model.Foo, true, 100) 

的能力等

2

一個簡單的例子:

public static class MyHelpers 
{ 
    public static MvcHtmlString MyTextBox(this HtmlHelper htmlHelper, string name, string value = "", bool canEdit = false, int width = 100) 
    { 
     if (canEdit) 
     { 
      return htmlHelper.TextBox(name, value, new { width = width.ToString() + "px" }); 
     } 
     else 
     { 
      return htmlHelper.TextBox(name, value, new { @readonly = "readonly", width = width.ToString() + "px" }); 
     } 
    } 
} 

然後註冊的web類.config或使用使用說明

@using test.Helpers 
@Html.MyTextBox("test") 
@Html.MyTextBox("test", "asdf") 
@Html.MyTextBox("test", "asdf", true, 500) 

結果:

<input id="test" name="test" readonly="readonly" value="" type="text" width="100px"> 
<input id="test" name="test" readonly="readonly" value="asdf" type="text" width="100px"> 
<input id="test" name="test" value="asdf" type="text" width="500px"> 
相關問題