关于c#:如何在.cs文件中调用@ Html.TextBoxFor

How can i call @Html.TextBoxFor in a .cs file

我正在为一个视图中的每个文本框设计一个项目,我有一个休闲的

1
2
3
4
5
    <label>Titlu</label>
   
        @Html.TextBoxFor(model => model.Name, new { @class ="form-control inline-input" })
   
    @Html.ValidationMessageFor(model => model.Name)

我想编写一个自定义帮助程序,将为我输出此帮助程序,但是当我不在视图中时,我不知道如何调用@ Html.TextBoxFor。

任何帮助将不胜感激。
谢谢

更新
我在控制器中发现了这个使用HtmlHelper的方法,但是它看起来很糟糕,必须有更好的方法


例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static class CustomHtmlHelper {

    public static MvcHtmlString MyFieldBox<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, String title) {

        StringBuilder sb = new StringBuilder();
        sb.AppendLine("");
        sb.AppendLine("");
        sb.AppendLine("<label>{0}</label>", title);
        sb.AppendLine("");
        sb.AppendLine( htmlHelper.TextBoxFor( expression, new { @class ="form-control inline-input" }) );
        sb.AppendLine("");
        sb.AppendLine( htmlHelper.ValidationMessageFor( expression );
        sb.AppendLine("");
        return new MvcHtmlString( sb.ToString() );
    }

}

用法:

1
<%= Html.MyFieldBox( m => m.Name,"Name" ) %>


如果仅在一个视图中使用,则另一种选择是使用razor htmlhelper语法。

您可以这样定义助手:

1
2
3
4
5
6
7
8
9
10
@helper MyTextBoxFor(System.Linq.Expressions.Expression<Func<ViewModelType, object>> expression )
{
   
        <label>Titlu</label>
       
            @Html.TextBoxFor(expression, new { @class ="form-control inline-input" })
       
        @Html.ValidationMessageFor(expression)
   
}

然后像这样使用它:

1
@MyTextBoxFor(m => m.Name)


如果适合您,可以尝试使用编辑器模板


http://msdn.microsoft.com/zh-cn/library/system.web.mvc.htmlhelper(v = vs.118).aspx

但是,如上所述,

The HtmlHelper class is designed to generate UI. It should not be used in controllers or models.