Click here to Skip to main content
15,902,832 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am calling a Javascript function from MVC Controller,

This is what i am using to call

C#
public ActionResult Index(string name, string email, string address)
        {
            ViewBag.Name = name;
            JavaScript("myfunction('123')");
            return View(ViewBag);
        }



and in javascript i have written this

JavaScript
<script>
    $(document).ready(
       function myfunction(e) {
           alert('Hello Test' + e);
       }
        );
</script>


And When i run it, it shows following unexpected result

"Hello Testfunction(e,t){return new x.fn.init(e, t,r)}"
Posted

1 solution

You can't call javascript from your controller as the controller executes on the server which generates html which is then sent to the browser to execute. Your .net code isn't "running inside" the browser so it can't interact with the DOM.

Secondly, the reason you're seeing what you're seeing in the alert box is because you are defining a function that is called when the document is "ready", ie everything has loaded and you want your jQuery functions to run. The function you defined accepts a param and alerts it, so when jQuery decides the DOM has loaded it calls your function (passing its Init event as the parm) and your function is showing that in an alert. When you alert a function you see the code in the function.

Thirdly, that's not how you use the JavaScript method, it is a return type that is really intended for actions called via AJAX if you want to pass some js to the client script to call on success. If you did want to use it you could do something like;

C#
public ActionResult Index()
{
    ViewBag.js = JavaScript("myfunction('123')");
    return View();
}


XML
<script>
    $(document).ready(function () {
        function myfunction(e) {
            alert('Hello Test' + e);
        }

        @Html.Raw(ViewBag.js.Script)
    });
</script>


However this breaks the MVC pattern, your controller shouldn't be generating js, you should be doing something like this

C#
public ActionResult Index()
{
    ViewBag.ID = 123;
    return View();
}


XML
<script>
    $(document).ready(function () {
        function myfunction(e) {
            alert('Hello Test' + e);
        }

        @if(ViewBag.ID != null)
        {
            <text>myfunction(@ViewBag.ID)</text>
        }
    });
</script>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900