Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Steve Sanderson's BeginCollectionItem not working in all cases... potential solution?

I'm working with Steve Sanderson's BeginCollectionItem utility to render a list of objects to be edited in MVC3, and it works great when you're rendering an entire collection from an iterator. My problem is coming when I'm trying to just add one new item to the collection, and return the html that represents that object. For some reason, my data annotations aren't being rendered in the html coming down from code.

Is there any fix available to this, or is there anything different, sans having to write the validation by-hand, that I can do to solve this issue?

Thanks.

like image 227
Richard B Avatar asked Oct 20 '11 16:10

Richard B


1 Answers

Things to consider:

  1. Data annotations will not be rendered unless a FormContext exists in whatever method you are using to create this additional object. If you are using a partial view, add the following to it at the top:

-

   if (this.ViewContext.FormContext == null) 
   {
       this.ViewContext.FormContext = new FormContext(); 
   } 
  1. If you are dynamically adding an item to the page via AJAX, then after you add your new item, you must clear the validation data in the DOM, and re-parse all of your validation elements, like so:

-

   $("form").removeData("validator");
   $("form").removeData("unobtrusiveValidation");
   $.validator.unobtrusive.parse("form");
like image 137
counsellorben Avatar answered Sep 22 '22 00:09

counsellorben