Replacement for TextAreaFor code in Asp.net MVC Razor

一世执手 提交于 2019-12-04 17:55:29

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