how to use jquery with razor syntax in asp.net mvc 5?

后端 未结 3 1037
失恋的感觉
失恋的感觉 2021-01-06 04:02

I need to use jQuery to add some elements dynamically. So I looked up in the internet and I found this. It is nice and working when there is plain html elements inside singl

3条回答
  •  执念已碎
    2021-01-06 04:25

    It is best to avoid generating jQuery/Javascript code with Razor. For many reasons your Javascript/jQuery code is better off in separate files (VS debugging/script bundling etc)

    Instead inject the templated HTML into a hidden part of the page. A dummy script block works great for this as the browser will just ignore an unknown script type:

    
    

    You can see what is generated with your DOM inspector to ensure the correct attributes are present.

    Then simply use that HTML from the template to add new buttons:

    $("#trItem").append($('#template').html());
    

    The only issue you need to resolve is any duplicate IDs and indexing for multiple items. I usually use raw HTML in the template (not Razor) and use placeholders for the various attributes that need renaming.

    e.g.

    
    
                                     
                  
提交回复
热议问题