Way to call function

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

LVL 11
HuaMin ChenProblem resolverAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Luis PérezSoftware Architect in .NetCommented:
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
HuaMin ChenProblem resolverAuthor Commented:
Thanks. As I need to raise the relevant popup, within Code-behind.
0
Alexandre SimõesManager / Technology SpecialistCommented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Luis PérezSoftware Architect in .NetCommented:
Can you post more info about your scenario?
0
HuaMin ChenProblem resolverAuthor Commented:
Thanks.
Alexandre,
Can I have details to call your codes in code-behind?
0
Alexandre SimõesManager / Technology SpecialistCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HuaMin ChenProblem resolverAuthor Commented:
Alexandre,
You are right as I want to show the popup in one event from code-behind.
0
HuaMin ChenProblem resolverAuthor Commented:
Alexandre,
how to raise the popup in one event from code-behind?
0
Alexandre SimõesManager / Technology SpecialistCommented:
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
Ray PaseurCommented:
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
Alexandre SimõesManager / Technology SpecialistCommented:
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
Kelvin McDanielSr. Developer/ConsultantCommented:
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
Alexandre SimõesManager / Technology SpecialistCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.