how to call javascript function from Controllers file in MVC ?
3 Answers
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.
1 Comment
jgauffin
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.
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)
1 Comment
Hitesh Prajapati
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); "
You can call JavaScript as well as content methods
public ActionResult Java_Script(){
return JavaScript("Message");
}
1 Comment
Mohammad Kanan
Could you clarify why you inverted the edit an April 20 which correctly formatted the code? you inverted back to incorrect code formatting!