I just been looking around online about calling a JavaScript function from code behind, from examples that I have seen you RegisterStartupScript method on a click event. But why would you want or need to do that instead of just wiring it up the OnClientClick event? Is there ever a need to call a JavaScript function from code behind?
Asked
Active
Viewed 46 times
0
-
http://stackoverflow.com/questions/4848678/how-to-call-javascript-function-from-code-behind – ashkufaraz Mar 17 '15 at 04:16
1 Answers
1
RegisterStartupScript is one of many options for an infinite number of scenarios. In the end, anything you can do with RegisterStartupScript can be done another way. I used to consider it a convenience, now I avoid it, separation of concerns and such higher stages of "enlightenment".
Mainly where I see RegisterStartupScript still in use is with custom controls that are expected to wire themselves up without the end-user knowing anything about them. See AjaxControlToolKit, UpdatePanel, ScriptManager, etc. They all require javascript but for obvious reasons do not expect you to include their client-side scripts or register them.
Random Scenario:
if (User.Identity.Name == "Frank")
RegisterStartupScript(this, GetType(), "Frank", "alert("Hey Frank, you owe me money!");
Alternative Scenario, have the server-side set a hidden field.
<input type="hidden" id="name" value="<%= User.Identity.Name %>" />
<script type="text/javascript">
$(document).ready(function() {
if ($("#name").val() == "Frank")
alert("Hey Frank, you owe me money!");
});
</script>

jtimperley
- 2,494
- 13
- 11
-
1One minor point of difference: in the second form, the JS code is rendered for every user, regardless of their name. In the former, only Frank sees the JS that alerts the intrusive reminder. This may or may not be an important difference to you in your scenario. – GregL Mar 17 '15 at 04:29
-
This explanation made sense. I can see why it could or would be used. It seemed rather odd from the examples I had seen, the examples were always using a button click event to call it and it didn't seem like there was a purpose for it. – Chris Mar 17 '15 at 04:37