![](/img/trans.png)
[英]How to use Html.TextAreaFor using many Ajax.BeginForms in same view
[英]How can I use Html.TextAreaFor() methods in my custom HtmlHelper?
我正在构建一个ASP.NET MVC 2网站,现在,我的视图中有丑陋的意大利面条代码,我想将其制作成自定义的HtmlHelper。 视图中的当前代码是:
<%switch (Model.fiFieldTypeID) %>
<%
{
case 1: // Text area
Response.Write(Html.Encode(Html.TextAreaFor(model => model.fiStrValue)));
Response.Write(Html.Encode(Html.ValidationMessageFor(model => model.fiStrValue)));
break;
case 2: // Text box
Response.Write( Html.Encode(Html.TextBoxFor(model => model.fiStrValue)));
Response.Write( Html.Encode(Html.ValidationMessageFor(model => model.fiStrValue)));
break;
etc....
我试图将这个代码封装成一个整洁的小HtmlHelper。 这就是我的开始:
public class FormHelpers
{
public static MvcHtmlString GetStreamFieldEditor(this HtmlHelper html, FieldInstance field)
{
string output = "";
switch (field.fiFieldTypeID)
{
case 1: // Text area
output += html.TextAreaFor(field=> field.fiStrValue).ToString();
etc....
我知道我的lamda是错的......但我更关心的是TextAreaFor
不能用作方法。 但是,可以使用普通的旧TextArea
。 我不想使用TextArea
因为我需要保留我的模型绑定。 如何在我的自定义html助手中使用TextAreaFor
, TextBoxFor
等?
这个怎么样:
public static class FormHelpers
{
public static MvcHtmlString GetStreamFieldEditor(
this HtmlHelper<YourModelType> html)
{
var model = html.ViewData.Model;
if (model.fiFieldTypeID == 1)
{
return html.TextAreaFor(x => x.fiStrValue);
}
return html.TextBoxFor(x => x.fiStrValue);
}
}
接着:
<%: Html.GetStreamFieldEditor() %>
<%: Html.ValidationMessageFor(x => x.fiStrValue) %>
using System.Web.Mvc.Html
添加。
编辑 :确保您引用System.Web.Mvc.dll v2.0或更高版本。
要修复lambda,您需要使用System.Linq.Expressions
手动生成表达式树。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.