Steve Sanderson's BeginCollectionItem not work

2019-03-13 15:34发布

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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-13 15:50

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");
查看更多
登录 后发表回答