开发者

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

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 开发者_Python百科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?


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> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜