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

巧了我就是萌 提交于 2019-12-03 09:55:41

问题


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.


回答1:


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");


来源:https://stackoverflow.com/questions/7839453/steve-sandersons-begincollectionitem-not-working-in-all-cases-potential-solu

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