gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:26:20 25 4
gpt4 key购买 nike

我想创建我自己的 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/

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