0

how to call javascript function from Controllers file in MVC ?

Hitesh Prajapati
  • 2,762
  • 8
  • 23
  • 29

3 Answers3

1

You CAN call it directly if you are using ajax.

Page A -> Ajax -> Controller -> Return javascript which invokes a method in Page A

    public ActionResult MyAjax(string message)
    {
        return JavaScript(string.Format("methodInPageA('{0}');", message.Replace("'", "\\'")));
    }

It might work without ajax too, but I haven't tried that.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • WHAT is not working? How do you invoke the controller method? What result do you get? I'm using this solution myself in different projects. As I said: It might only work with ajax. – jgauffin Nov 26 '10 at 12:04
0

You wont be able to call it directly you will have to call the javascript function onLoad document or other page event (like button click or something)

wael34218
  • 4,860
  • 8
  • 44
  • 62
  • in mvc, onload is not working that i know but it's one class file only so it doesn't work.Here i have " ScriptManager.RegisterStartupScript(@@@@@@,this.GetType(),"setMenuItem","setMenuItem();",true); " – Hitesh Prajapati Nov 26 '10 at 11:06
0

You can call JavaScript as well as content methods

 public ActionResult Java_Script(){
      return JavaScript("Message");
 }
  • Could you clarify why you inverted the edit an April 20 which correctly formatted the code? you inverted back to incorrect code formatting! – Mohammad Kanan Aug 06 '18 at 09:38