gpt4 book ai didi

asp.net-mvc-3 - 使用 MVC 3 创建自定义 UI 元素

转载 作者:行者123 更新时间:2023-12-02 18:46:34 25 4
gpt4 key购买 nike

在我的项目中,我有一个要求,即取决于特定条件的某些字段应该是可编辑的或只读的。

所以我认为在每个领域都这样做是一种矫枉过正

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

我决定使用编辑器模板,但后来我意识到宽度无法固定,所以我想知道向编辑器模板发送参数的最佳方式是什么?它还应该处理宽度可能未定义的情况,并且根本不使用宽度属性。我发现 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 *@

最佳答案

kapsi 的答案很好,但是如果您想在强类型 View 中使用助手,这里是基本语法。这有点草率,但您可以根据需要添加重载。

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));
}
}

当然,这样,您就可以对 View 元素进行强类型化

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

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

等等

关于asp.net-mvc-3 - 使用 MVC 3 创建自定义 UI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6293824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com