MVC3剃刀Html.TextBoxFor:我可以让多线样TextAreaFor? [英] MVC3 Razor Html.TextBoxFor: Can I make it Multi-Line like TextAreaFor?

查看:449
本文介绍了MVC3剃刀Html.TextBoxFor:我可以让多线样TextAreaFor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个帖子:更改Html.TextBox <大小/一>

但我不能改变 Html.TextAreaFor(),因为它不具有的属性为我设定一个动态的默认值(我正在编辑页面,我要在随后可以修改当前数据)的字段动态地继续进行。我也似乎无法得到,即使我换到EditorFor工作 [数据类型(DataType.MultilineText)] 在我的视图模型(一切它似乎改变为textboxfor和我的默认值不显示)。

我的编辑视图将包含两个型号,一个空的形式的视图模型( OfferForm )来填充屏幕上的各个领域,并在报价包含当前数据模式。我想拥有的 OfferForm ,并动态与报价模型数据的内容填充。

下面是我的html:

 &LT; D​​IV CLASS =内联&GT;
                    &LT; D​​IV CLASS =行内编辑器标签容器&GT;
                        &LT; D​​IV CLASS =编辑标记&GT;
                            @ Html.LabelFor(型号=&GT; model.OfferForm.Description)
                        &LT; / DIV&GT;
                    &LT; / DIV&GT;
                    &LT; D​​IV CLASS =行内编辑器场容器&GT;
                        &LT; D​​IV CLASS =主编场&GT;
                            @ Html.TextBoxFor(型号=&GT; model.OfferForm.Description,新{@Value = @ Html.DisplayFor(型号=&GT; model.Offer.Description)})
                            @ Html.ValidationMessageFor(型号=&GT; model.Offer.Description)
                        &LT; / DIV&GT;
                    &LT; / DIV&GT;
                &LT; / DIV&GT;
                &LT; D​​IV CLASS =内联&GT;
                    &LT; D​​IV CLASS =行内编辑器标签容器&GT;
                        &LT; D​​IV CLASS =编辑标记&GT;
                            @ Html.LabelFor(型号=&GT; model.OfferForm.SMSText)
                        &LT; / DIV&GT;
                    &LT; / DIV&GT;
                    &LT; D​​IV CLASS =行内编辑器场容器&GT;
                        &LT; D​​IV CLASS =主编场&GT;
                            @ Html.TextBoxFor(型号=&GT; model.OfferForm.SMSText,新{@Value = @ Html.DisplayFor(型号=&GT; model.Offer.SmsText)})
                            @ Html.ValidationMessageFor(型号=&GT; model.Offer.SmsText)
                        &LT; / DIV&GT;
                    &LT; / DIV&GT;
                &LT; / DIV&GT;

有没有一种方法来设置一个多行,在属性中的 Html.TextBoxFor()


解决方案

进行最简单的方法是创建如下所示的HTML扩展方法

 公共静态类HtmlTextAreaExtensions {    公共静态IHtmlString TextAreaFor&LT;的TModel,TProperty&GT;(此的HtmlHelper&LT;的TModel&GT;的HtmlHelper,防爆pression&LT; Func键&LT;的TModel,TProperty&GT;&GT;前pression,诠释行,诠释COLS,对象htmlAttributes = NULL,字符串值= NULL){
        返回TextAreaFor&LT;的TModel,TProperty&GT;(的HtmlHelper,前pression,行,COLS,HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),价值);
    }    公共静态IHtmlString TextAreaFor&LT;的TModel,TProperty&GT;(此的HtmlHelper&LT;的TModel&GT;的HtmlHelper,防爆pression&LT; Func键&LT;的TModel,TProperty&GT;&GT;前pression,诠释行,诠释COLS,IDictionary的&LT;字符串,字符串&GT; htmlAttributes = NULL,字符串值= NULL){
        VAR modelMetadata = ModelMetadata.FromLambdaEx pression(如pression,htmlHelper.ViewData);
        变量名称=前pressionHelper.GetEx pressionText(如pression);        字符串全名= htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(名);        字典&LT;字符串对象&gt; rowsAndColumns =新词典&LT;字符串对象&gt;();
        如果(行大于0){
            rowsAndColumns.Add(行,rows.ToString(CultureInfo.InvariantCulture));
        }其他{
            rowsAndColumns.Add(行,5);
        }
        如果(COLS大于0){
            rowsAndColumns.Add(COLS,cols.ToString(CultureInfo.InvariantCulture));
        }其他{
            rowsAndColumns.Add(COLS,20);
        }
        TagBuilder tagBuilder =新TagBuilder(文本域);
        tagBuilder.GenerateId(全名);
        tagBuilder.MergeAttributes(htmlAttributes,真);
    tagBuilder.MergeAttributes(rowsAndColumns,FALSE); //唯一力量显行/ COLS
        tagBuilder.MergeAttribute(名,全名,真实);        //如果有一个名为字段的任何错误,我们添加CSS属性。
        ModelState中的ModelState;
        如果(htmlHelper.ViewData.ModelState.TryGetValue(全名,出的ModelState)及&放大器; modelState.Errors.Count大于0){
            tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
        }        tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(名));        字符串值;
        如果(值!= NULL){
            值=价值;
        }否则如果(的ModelState = NULL&放大器;!&安培;!modelState.Value = NULL){
            值= modelState.Value.AttemptedValue;
        }否则如果(modelMetadata.Model!= NULL){
            值= modelMetadata.Model.ToString();
        }其他{
            值=的String.Empty;
        }        //当一个TextArea呈现的第一个换行符总是修剪,所以我们增加多一件。
        //的情况下所呈现的价值是一样的东西为\\ r \\ nHello。
        tagBuilder.SetInnerText(Environment.NewLine +值);        返回新HtmlString(tagBuilder.ToString(TagRenderMode.Normal));
    }
}

您可以然后调用它:

  @ Html.TextAreaFor(F =&GT; f.ModelProperty,值= f.SomeOtherModelProperty)

它仅支持基本功能,什么不是。实际的标记生成从MVC3源略有改动,以支持传递的价值拉动。这应该适用于大多数情况下,但你可能需要增加更多的覆盖。这是不是很......干净,但应该让你去。 :)

要获得延伸到你的剃须刀意见里面显示你的浏览目录中编辑的Web.config 并添加命名空间(不是类名),你把这个类。那么它应该在IntelliSense中显示出来。

I've already seen this post: Changing the size of Html.TextBox

But I cannot change to Html.TextAreaFor() because it does not have an attribute for me to set a dynamic default value (I am making an edit page that I want to dynamically fill in the fields of the current data which can then be modified). I also can't seem to get the EditorFor to work even if I change to [DataType(DataType.MultilineText)] in my viewmodel (all it does it seem to change to textboxfor and my default values do not show up).

My edit view takes in a viewmodel containing two models, an empty form (OfferForm) to be filled with the onscreen fields, and the offer model containing the current data. I want to have textfields for the OfferForm, and dynamically fill them with the contents of the offer model's data.

Here is my html:

<div class="InLine">
                    <div class="InLine editor-label-container">
                        <div class="editor-label">
                            @Html.LabelFor(model => model.OfferForm.Description)
                        </div>
                    </div>
                    <div class="InLine editor-field-container">
                        <div class="editor-field">
                            @Html.TextBoxFor(model => model.OfferForm.Description, new { @Value = @Html.DisplayFor(model => model.Offer.Description)})
                            @Html.ValidationMessageFor(model => model.Offer.Description)
                        </div>
                    </div>
                </div>
                <div class="InLine">
                    <div class="InLine editor-label-container">
                        <div class="editor-label">
                            @Html.LabelFor(model => model.OfferForm.SMSText)
                        </div>
                    </div>
                    <div class="InLine editor-field-container">
                        <div class="editor-field">
                            @Html.TextBoxFor(model => model.OfferForm.SMSText, new { @Value = @Html.DisplayFor(model => model.Offer.SmsText)})
                            @Html.ValidationMessageFor(model => model.Offer.SmsText)
                        </div>
                    </div>
                </div>

Is there a way to set a "multiline" attribute in the Html.TextBoxFor()?

解决方案

The simplest way to proceed would be to create an Html extension method like the following

public static class HtmlTextAreaExtensions {

    public static IHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int cols, object htmlAttributes = null, string Value = null) {
        return TextAreaFor<TModel, TProperty>(htmlHelper, expression, rows, cols, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), Value);
    }

    public static IHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int cols, IDictionary<string, string> htmlAttributes = null, string Value = null) {
        var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var name = ExpressionHelper.GetExpressionText(expression);

        string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

        Dictionary<string, object> rowsAndColumns = new Dictionary<string, object>();
        if (rows > 0) {
            rowsAndColumns.Add("rows", rows.ToString(CultureInfo.InvariantCulture));
        } else {
            rowsAndColumns.Add("rows", "5");
        }
        if (cols > 0) {
            rowsAndColumns.Add("cols", cols.ToString(CultureInfo.InvariantCulture));
        } else {
            rowsAndColumns.Add("cols", "20");
        }
        TagBuilder tagBuilder = new TagBuilder("textarea");
        tagBuilder.GenerateId(fullName);
        tagBuilder.MergeAttributes(htmlAttributes, true);
    tagBuilder.MergeAttributes(rowsAndColumns, false);  // Only force explicit rows/cols
        tagBuilder.MergeAttribute("name", fullName, true);

        // If there are any errors for a named field, we add the CSS attribute.
        ModelState modelState;
        if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0) {
            tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
        }

        tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name));

        string value;
        if (Value != null) {
            value = Value;
        } else if (modelState != null && modelState.Value != null) {
            value = modelState.Value.AttemptedValue;
        } else if (modelMetadata.Model != null) {
            value = modelMetadata.Model.ToString();
        } else {
            value = String.Empty;
        }

        // The first newline is always trimmed when a TextArea is rendered, so we add an extra one
        // in case the value being rendered is something like "\r\nHello".
        tagBuilder.SetInnerText(Environment.NewLine + value);

        return new HtmlString(tagBuilder.ToString(TagRenderMode.Normal));
    }
}

You could then call it:

@Html.TextAreaFor(f => f.ModelProperty, Value=f.SomeOtherModelProperty)

It only supports basic features and what not. The actual tag generation was pulled from Mvc3 source with slight changes to support passing the value in. This should work for most cases but you might need to add more overrides. This isn't very...clean but should get you going. :)

To get the extension to show up inside your razor views you edit the Web.config within the Views directory and add the namespace (not the class name) where you put this class. It should then show up in intellisense.

这篇关于MVC3剃刀Html.TextBoxFor:我可以让多线样TextAreaFor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆