Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Error: conditional compilation is turned off in MVC2 View

I am trying to call a JavaScript function on click in a 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, its working fine. But when I have two paramaters its not.I am getting this error:

conditional compilation is turned off.
like image 533
Rajesh Avatar asked Jan 21 '23 18:01

Rajesh


2 Answers

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

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

This being said your parameters need to be properly encoded and I wouldn't pass them likse this. I would serialize them as JSON object to ensure that everything is OK. 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);
}
like image 76
Darin Dimitrov Avatar answered Jan 30 '23 12:01

Darin Dimitrov


I'm guessing o.ba_Object_Code is not a number? Try putting quotes around it:

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

You could also write this function like this:

<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;
});
like image 28
TheRightChoyce Avatar answered Jan 30 '23 13:01

TheRightChoyce