gpt4 book ai didi

c# - 如何在自定义 HtmlHelper 中使用 Html.TextAreaFor() 方法?

转载 作者:太空宇宙 更新时间:2023-11-03 22:18:46 25 4
gpt4 key购买 nike

我正在构建一个 ASP.NET MVC 2 网站,现在,我的 View 中有难看的意大利面条代码,我想将其制作成自定义 HtmlHelper。 View 中的当前代码是:

            <%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 因为我需要保留我的模型绑定(bind)。如何在我的自定义 html 帮助程序中使用 TextAreaForTextBoxFor 等?

最佳答案

这个怎么样:

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) %>

关于c# - 如何在自定义 HtmlHelper 中使用 Html.TextAreaFor() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3980370/

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