asp.net mvc TextAreaFor is not getting validated a

2019-06-19 01:57发布

I have a data entry field where I'm gathering notes. The note data element is required for each note. Here's my model:

public interface INoteDataEntryViewModel : IMobilePageDataContract
{
    int CourseId { get; set; }

    [Required(ErrorMessage = @"Note is required")]
    String Note { get; set; }

    [DisplayName(@"Note Date")]
    DateTime NoteDate { get; set; }
}

You can see that I have the Required attribute for the Note property.

I'm using Razor to display the data entry form element:

<div data-role="fieldcontain">
    @Html.LabelFor(m => m.Note)
    @Html.TextAreaFor(m => m.Note)
    @Html.ValidationMessageFor(m => m.Note)
</div>

When I use "@Html.TextAreaFor" then there is no validation for the required field and i can submit the form. However, if I change to "@Html.TextBoxFor", then validation happens for the required field and I cannot submit the form. Any ideas on why validation fails for TextAreaFor? I'm using unobtrusive ajax and am jQueryMobile.

Thanks for your help.

1条回答
你好瞎i
2楼-- · 2019-06-19 02:06

The client-side validation does not work for the Html.TextAreaFor() helper, here is the related issue reported on Codeplex.

To make it work, you have to decorate the 'Note' property with the [DataType(DataType.MultilineText)] attribute. And in the view, use Html.EditorFor() helper instead of the Html.TextAreaFor() helper mehthod.

Updated Model:

public interface INoteDataEntryViewModel : IMobilePageDataContract
{
    int CourseId { get; set; }

    [Required(ErrorMessage = @"Note is required")]
    [DataType(DataType.MultilineText)]
    String Note { get; set; }

    [DisplayName(@"Note Date")]       
    DateTime NoteDate { get; set; }
}

View:

<div data-role="fieldcontain">
    @Html.LabelFor(m => m.Note)
    @Html.EditorFor(m => m.Note)
    @Html.ValidationMessageFor(m => m.Note)
</div>
查看更多
登录 后发表回答