自定义文本框 Asp.net 带包装器的 MVC 助手

Custom TextBox Asp.net MVC Helper with wrapper

我想创建我自己的 TextBox Helper,它做一件简单的事情:用一些 div 和标签包装输入元素,如下所示:

<div class="col-xs-12">
  <label>field name</label>
  <div>
    <input id='myId' name='MyName' type='text' value='myValue'>
  </div>
</div>

在视图中,我想这样称呼它:

@Html.TextBox("Name")

我该怎么做?有一种方法可以在我的助手中调用 base class?


更新:更好的解决方案

在 Krishina 回答后,我得到了一个更好的方法,使用这样的代码:

public static MvcHtmlString CliTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string LabelText, object htmlAttributes)
    {
        var baseFormat = htmlHelper.TextBoxFor(expression, format: null, htmlAttributes: htmlAttributes);
        var errors = htmlHelper.ValidationMessageFor(expression, "", new { @class = "text-danger" }).ToString();

        if (!string.IsNullOrEmpty(errors))
            errors = "<div>" + errors + "</div>";

        var wrap = String.Format(
            "<div class='col-xs-12'>" +
            "<label>{0}</label>" +
            "<div>{1}</div>"+
            "{2}" +
            "</div>", LabelText, baseFormat.ToString(), errors);

        return new MvcHtmlString(wrap);
    }

就这样,我一直使用TextBoxFor来生成基础输入元素。

您需要为您的文本框创建自定义 Html 助手,如下所示。

namespace MvcApplication.Helpers
{
    public static class TextboxExtensions
    {
        public static HtmlString CustomTextBox(this HtmlHelper helper, string labelName, NameValueCollection parameters)
        {
            var returnValue = string.Empty;
            if (parameters == null || parameters.Count <= 0) return new HtmlString(returnValue);

            var attributes = parameters.AllKeys.Aggregate("", (current, key) => current + (key + "=" + "'" + parameters[key] + "' "));

            returnValue = String.Format("<div class='col-xs-12'><label>{0}</label>" +
                                        "<div><input " + attributes + "></div></div>", labelName);

            return new HtmlString(returnValue);
        }
    }
}

要使用上述扩展方法,请按照以下步骤操作

在您的 MVC 视图中,将 using 语句写在顶部

@using MvcApplication.Helpers

然后,编写Html helper 如下

@Html.CustomTextBox("Name", new NameValueCollection { {"id", "myId"}, {"value", "myValue"} })

注意:您可以使用 json 或其他类型来代替 NameValueCollection。