Replacement for TextAreaFor code in Asp.net MVC Ra

2019-04-13 18:45发布

问题:

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;
}