MVC 3 client-side validation on collection with data annotations — not working

两盒软妹~` 提交于 2019-12-19 10:45:16

问题


I am trying to get client side validation to work on my model -- so far it's not working.

My model has a property that's a collection:

public class NewsEventsModel
{
    public List<NewsItemDetails> newsItems { get; set; }
    public int pageNumber { get; set; }
    public int totalPages { get; set; }
    public bool canManageNews { get; set; }
    public long userID { get; set; }
}

and NewsItemDetails is defined thusly:

public class NewsItemDetails
{
    public long itemID { get; set; }

    public long postedByID { get; set; }

    public DateTime datePosted { get; set; }

    [Required(ErrorMessage = "Please enter news or event text")]
    [StringLength(100)]
    [RegularExpression(RegExpressions.freeTextRestrict)]
    public string newsBody { get; set; }

    [StringLength(50)]
    [RegularExpression(RegExpressions.freeTextRestrict)]
    public string newsTitle { get; set; }
}

I send NewsEventsModel over to the view. Then in my view I include

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>  

Then in the view code I have

   for (int j = 0; j < Model.newsItems.Count(); j++)
   {

      /// bunch of stuff
      // then:
     <div class="editblock">
       @Html.TextAreaFor(model => model.newsItems[j].newsBody, new { @class = "formtextem", id = editBoxID, rows = "10", style = "width: 54em" })
       @Html.ValidationMessageFor(model => model.newsItems[j].newsBody)
     </div> 
   } 

But when I delete all the text in the text area and click save, the "required" message does not appear .. nor do any messages appear when I violate any of the other rules.

However, the client-side validation does work if I put validation annotation on one of the properties in the top-level NewsEventsModel, and then include it as a textbox in the view. It just doesn't work for the lower-level NewsItemDetails class.

What am I missing here?


回答1:


Try using Editor Templates in your view:

@Html.EditorFor(x => x.newsItems)

and inside ~/Views/Shared/EditorTemplates/NewsItemDetails.cshtml:

@model AppName.Models.NewsItemDetails

// bunch of stuff
// then:
<div class="editblock">
    @Html.TextAreaFor(model => model.newsBody, new { @class = "formtextem", id = editBoxID, rows = "10", style = "width: 54em" })
    @Html.ValidationMessageFor(model => model.newsBody)
</div> 


来源:https://stackoverflow.com/questions/5239995/mvc-3-client-side-validation-on-collection-with-data-annotations-not-working

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