c# - 带有包装器的自定义 TextBox Asp.net MVC Helper

标签 c# asp.net-mvc razor

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

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

在 View 中,我想这样调用它:

@Html.TextBox("Name")

我该怎么做?有办法在我的助手中调用基类吗?


更新:更好的解决方案

在 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 Helper,如下所示。

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 View 中,将 using 语句写在顶部

@using MvcApplication.Helpers

然后,编写Html helper如下

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

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

关于c# - 带有包装器的自定义 TextBox Asp.net MVC Helper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29108847/

相关文章:

c# - 如何让用户在 C# EF4.1 Code First 中动态指定数据库提供程序和连接详细信息?

.net - 使用 jquery 填充下拉菜单并设置从 .NET SelectList 中选择的内容

c# - 从 HttpPostedFileBase 获取文件路径

asp.net-mvc-3 - ASP.NET MVC : Html. EditorFor 和多行文本框

asp.net-mvc - ASP.NET MVC - 如何在 EditorTemplates 中使用必需的消息

c# - FileHelpers 库 CSV - 为什么总是从右侧的最后一列中删除一个字母?

c# - AspNetCore 3.1 路由 AmbigouslyMatchException

c# - 未使用 ASP.NET MVC EditorTemplate

c# - 无法从内容页访问母版页的 &lt;input type ="button">

c# - MVC4 Web API返回带有特殊字符的json propertykey字符串