Replacement for TextAreaFor code in Asp.net MVC Razor

China☆狼群 提交于 2019-12-06 09:19:53

问题


Following is my model property

[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
public string ShortDescription { get; set; }

And following is my corresponding View code

@Html.TextAreaFor(model => model.Product.ShortDescription, new { cols = "50%", rows = "3" })
@Html.ValidationMessageFor(model => model.Product.ShortDescription)

And this is how it shows in the browser, the way i want.

Now, since there is a bug in Microsoft's MVC3 release, I am not able to validate and the form is submitted and produces the annoying error.

Please tell me the work around or any code that can be substituted in place of TextAreaFor. I can't use EditorFor, because with it, i can't use rows and cols parameter. I want to maintain my field look in the browser. Let me know what should be done in this case


回答1:


In the controller action rendering this view make sure you have instantiated the dependent property (Product in your case) so that it is not null:

Non-working example:

public ActionResult Foo()
{
    var model = new MyViewModel();
    return View(model);
}

Working example:

public ActionResult Foo()
{
    var model = new MyViewModel
    {
        Product = new ProductViewModel()
    };
    return View(model);
}

Another possibility (and the one I recommend) is to decorate your view model property with the [DataType] attribute indicating your intent to display it as a multiline text:

[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
[DataType(DataType.MultilineText)]
public string ShortDescription { get; set; }

and in the view use an EditorFor helper:

@Html.EditorFor(x => x.Product.ShortDescription)

As far as the rows and cols parameters that you expressed concerns in your question about, you could simply use CSS to set the width and height of the textarea. You could for example put this textarea in a div or something with a given classname:

<div class="shortdesc">
    @Html.EditorFor(x => x.Product.ShortDescription)
    @Html.ValidationMessageFor(x => x.Product.ShortDescription)
</div>

and in your CSS file define its dimensions:

.shortdesc textarea {
    width: 150px;
    height: 350px;
}


来源:https://stackoverflow.com/questions/8723028/replacement-for-textareafor-code-in-asp-net-mvc-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!