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 pilation is turned off.
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 pilation is turned off.
Share
Improve this question
edited Jan 13, 2011 at 22:58
Skilldrick
70.9k36 gold badges182 silver badges231 bronze badges
asked Jan 13, 2011 at 22:54
RajeshRajesh
2,5023 gold badges25 silver badges33 bronze badges
1
- Can you show us the rendered HTML? I.e. what do you see when you view source? – Skilldrick Commented Jan 13, 2011 at 22:59
2 Answers
Reset to default 7I 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);
}
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;
});