?
Solved

Way to call function

Posted on 2014-08-07
13
Medium Priority
?
169 Views
Last Modified: 2014-08-10
Hi,
what is the way to call this function below, within code-behind?

    <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript">
        ...

        function openPopup() {
            $("#myPanel").dialog("open");
        }
    </script>
    ...

Open in new window

0
Comment
Question by:HuaMinChen
  • 5
  • 4
  • 2
  • +2
13 Comments
 
LVL 25

Expert Comment

by:Luis Pérez
ID: 40245723
Why do you want to call it from code-behind? Code-behind is server-side code, while your "openPopup" function is client-side code.
0
 
LVL 11

Author Comment

by:HuaMinChen
ID: 40245726
Thanks. As I need to raise the relevant popup, within Code-behind.
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40245729
As @Luis said, there's no way to call client-side code from the back-end.
There are tho a lot of trick that can be used to simulate the behavior.

In this case I believe you just want to open the popup when the page loads?
If so, something like this will do the trick:
$(document).ready(function(){
$("#myPanel").dialog("open");
});

Open in new window

just put this code anywhere in the javascript file that is loaded with the page.
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
LVL 25

Expert Comment

by:Luis Pérez
ID: 40245730
Can you post more info about your scenario?
0
 
LVL 11

Author Comment

by:HuaMinChen
ID: 40245737
Thanks.
Alexandre,
Can I have details to call your codes in code-behind?
0
 
LVL 30

Accepted Solution

by:
Alexandre Simões earned 630 total points
ID: 40245739
If this is related to showing a popup based on something that you did on the server you can put a flag value on an input hidden and check it's value upon page load:
$(document).ready(function(){
  if($('#showPopup').val() === 'true'){
    $("#myPanel").dialog("open");
  }
});

Open in new window

0
 
LVL 11

Author Comment

by:HuaMinChen
ID: 40245740
Alexandre,
You are right as I want to show the popup in one event from code-behind.
0
 
LVL 11

Author Comment

by:HuaMinChen
ID: 40245746
Alexandre,
how to raise the popup in one event from code-behind?
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40245748
Ok so just keep in mind that you can't call it from the code-behind.
So lets assume that you have a webform and you do a postback.
In this postback you do some validations and something isn't right so you want to show a popup to the user.

One way to do this is to add an input hidden to your page that by default has no value.
Upon server-side validation you set this control value to "true" and do nothing else.
Coming back to the page a new page load will be executed and the code I posted above will be execute (client-side)
That code searches for a control with a client id = "showPopup"
If this control has the value "true" the popup will be shown.

You can even use the same technique to pass the message you want to show, for instance the exact validation error that occurred.

I hope this was clear enough.
You really can't call JavaScript functions from the backend.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40245807
I don't have time to work on a low-points question, but I can see that there is a fundamental misunderstanding here about the nature of the client/server relationship.  Hopefully this article can help clear that up.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

If you want to learn jquery, this is a good place to start.
http://learn.jquery.com/
http://try.jquery.com/

This is also useful:
http://www.amazon.com/Learning-jQuery-Edition-Jonathan-Chaffer/dp/1849516545
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40245824
Just to add to what @Ray said, if you don't have the skills to do this then lean JavaScript even before touching jQuery
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 40251827
Wow, the contempt in these "Expert" responses! :(

While I agree with the overall theme that it's not a "great" idea to mix your server-side and client-side executable code... meaning use the client-side event modeling to do client-side stuff (I'll explain more in a bit)... it certainly is possible to trigger client-side code via either a postback or an Ajax postback. It would be far better to make your page/view aware of the conditions which would result in a pop up and then, once met, execute the pop up. That way you're not mixing server and client-side code -- rather, the flow is all one-way (towards the page/view).

If you're using WebForms:
http://msdn.microsoft.com/en-us/library/bb350750(v=vs.110).aspx <-- make sure your read that one carefully as it suggests a couple of different strategies depending upon your implementation.

If you're using MVC:
This is a bit trickier. As near as I can tell there is no Page object and therefore no ClientScriptManager... so one strategy is to use a combination of jQuery and a JsonResult Controller method that includes your script which we then emit to the view.

In your view:
<button onclick="executeDynamicJs()">Test Dynamic Js</button>
<div id="dynamicJsResultPanel"></div>

<script type="text/javascript">
    function executeDynamicJs() { 
        var url = "@Url.Action("GetDynamicJs", "Home")";
        var data = { dynamicMessage: "BOOM-SHOCK-A-LOCKA!" };
        $.get(url,
            data,
            function (data, textStatus, jqXHR) {
                alert("request result is: " + textStatus);

                // this is the "consume in the success function" handling described below.
                eval(data.scriptNoTags);

                // this is the "embed this in the page" handling described below.
                $("#dynamicJsResultPanel").html(data.script); // this is the 
            },
            "json");
    }
</script>

Open in new window

In your Controller:
public JsonResult GetDynamicJs(string dynamicMessage)
{
    var returnMessage = string.IsNullOrWhiteSpace(dynamicMessage) ? "it works!" : dynamicMessage;
    var scriptBody = string.Format("alert('{0} (from the {1})');", returnMessage, "{0}");
    return Json(
        new
        {
            script = string.Format("<script>{0}</script>", string.Format(scriptBody, "dynamicJsResultPanel")),
            scriptNoTags = string.Format(scriptBody, "handleSuccess() function"),
        },
        JsonRequestBehavior.AllowGet);
}

Open in new window


Note: all of this code, while tested, is contrived. The important parts to note are the fact that we push a get request to the Controller and the corresponding Controller method returns a JsonResult which we can act upon. I've provided but a straight "consume in the success function" example as well as an "embed this in the page" example for handling the response.

Ultimately, the problem with this approach is that the server-side code might need to know things about the view that it shouldn't necessarily know. That can easily get you into trouble.

Also, you should NEVER allow a server-side function to receive ANY uncontrolled input and then emit a response back to the UI; that is how script-kiddies make their money.

The example I provide does this very naughty thing only to show that you can pass parameters for your server-side code to interpret and act upon. An immediate suggestion then is that you use your parameters to tell the Controller method everything it needs to know to construct the script (such as what will be emitting the script, what functions on the page to call, etc.).

IHTH!
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40252052
No contempt here and everything I said is true.
Nothing you proposed actually calls a function from server side which is, in fact, impossible (not even with WebSockets).

Like I said there are a lot of tricks to overcome this but for me, the one that puts things where they belong is the one I proposed. That is, passing a flag from server-side, put it in an input hidden, and execute the code client-side based on that flag.

Injecting JavaScript like you propose in fact works but creates a layer of "magic" hard to maintain and debug.

Last point, related to JavaScript skills, it's nothing but true.
JavaScript is a very easy going language but a very tricky one also. Mastering it is essential as well as understanding how data goes back and forth, specially in the .Net world where a lot of "backstage" things are hidden from the developers.

Cheers!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question