ACP
ACP

Reputation: 35268

calling a jquery function from asp.net mvc action

After posting a form to database is it possible to call a jquery from asp.net mvc.....

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                //Insert to db
                //Call a jquery function 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

should i use ScriptManager.RegisterClientScriptBlock after the insert or any other way to do this... Any suggestion...

Upvotes: 2

Views: 3752

Answers (1)

Omar
Omar

Reputation: 40182

No. You cannot call a jQuery function from an action. The way to do this in MVC is to simply add the function in the View's .aspx page and just wrap it in the $(document).ready(function(){}) (or w/e the function is for your library) so that when the page fully loads, the function will be called.

It is important to note that with MVC you have complete control of the HTML (JavaScript included) output and you should utilize that. While in WebForms its best to avoid using inline tags <% %>, in MVC, you're expected to use them to generate the HTML you want.

So, assuming that the Insert to db will return something, like an ID, you can place this ID value in the ViewData or TempData since you're using RedirectToAction and then use it to call the function.

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection collection)
    {
        int newID = InsertToDBAndReturnID();
        ViewData["MyID"] = newID;
        return View();
    }

And somewhere in the .aspx page that is used for the Create action:

   <script type="text/javascript">
       $(document).ready(function() {

          // I have direct access to the "MyID" value from the action
          // so I can utilize it to write any JavaScript with it
          $('#'+<%: ViewData["MyID"] %>).click(function(){
              alert('You clicked the control with the new ID');
          });

       });
   </script>

When the page is rendered, <%: ViewData["MyID"] %> is replaced with the actual value generated in the action.

Upvotes: 1

Related Questions