Wednesday, 26 February 2014

Javascript function: Sending MVC Razor parameter containing special characters

I am working on MVC Razor. I have to call a javascript function loadHierarchyData  on click event. It works fine if we use the Razor format @item.HierarchyName which allows the parameters to be passed to the function successfully.
<div class="tile" onclick="javascript:loadHierarchyData('@item.HierarchyName',@item. HierarchyDetailId,'@item.HierarchyCode')" >

However we face issue when the dynamic parameter contains special characters. In this example our parameter contains ‘ character. The solution is to include \\ character in front of the special character as shown in the below example.
<div class="tile" onclick="javascript:loadHierarchyData('@item.HierarchyName.Replace("'","\\'")',@item. HierarchyDetailId,'@item.HierarchyCode')" >