2011-06-09 66 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">