JavaScript error: conditional compilation is disabled in MVC2 View

I am trying to call a JavaScript function when I click on the MVC2 view page.

<a onclick=" SelectBenefit(<%=o.ba_Object_id %>,<%=o.ba_Object_Code %>)" href="#">Select</a> 

Javascript function

  function SelectBenefit(id,code) { alert(id); alert(code); } 

Here ba_Object_Id and Code are the values ​​from the ViewModel. If I use SelectBenefit(<%=o.ba_Object_id %>) in this way, it works fine. But when I have two parameters, it is not. I get this error:

 conditional compilation is turned off. 
+4
source share
2 answers

I think you need to put quotes around the second parameter if this is a string:

 <a onclick=" SelectBenefit(<%=o.ba_Object_id %>, '<%=o.ba_Object_Code %>')" href="#">Select</a> 

This suggests that your parameters must be correctly encoded, and I will not pass them. I would serialize them as a JSON object to make sure everything is in order. Like this:

 <a onclick="SelectBenefit(<%= new JavaScriptSerializer().Serialize(new { id = o.ba_Object_id, code = o.ba_Object_Code }) %>)" href="#">Select</a> 

and then the SelectBenefit function might look like this:

 function SelectBenefit(benefit) { alert(benefit.id); alert(benefit.code); } 
+7
source

I assume o.ba_Object_Code not a number? Try putting quotes there:

 <a onclick="SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>')" href="#">Select</a> 

You can also write this function as follows:

 <a href="javascript:SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>');">Select</a> 

Or use jQuery (best approach, imo):

 $('#yourlinkid').click(function(){ SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>'); return false; }); 
+2
source

Source: https://habr.com/ru/post/1335482/


All Articles