如何从MVC控制器方法调用javascript函数 [英] How to call the javascript function from MVC controller method

查看:779
本文介绍了如何从MVC控制器方法调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 在ASP.net MVC中
我在控制器中有一个方法
从这种方法中,我必须在客户端调用javascript函数
如何从MVC控制器方法

Hi In ASP.net MVC
I Have a method in controller
from this method i have to call the javascript function in client side
How to call the javascript function from MVC controller method

推荐答案

调用javascript函数,恐怕您无法做到这一点.您无法从服务器端控制器AFAIK调用客户端javascript函数.
I''m afraid you can''t do this. You can''t call Client side javascript function from Server side controller, AFAIK.


这可以通过SignalR完成,请参见
It can be done with SignalR, See Scott Hanselmans blog[^] on Asynchronous scalable web applications with real-time persistent long-running connections with SignalR

Regards
Piet


您可以做两件事,其中之一就是您的意思,除非您对客户端/服务器的分离终究感到困惑.

There are two things you can do, one of which is what you mean, unless you''re terminally confused about client/server separation.


  1. 您想在控制器方法返回"时(即在提供页面时)尽快运行一些客户端javascript.答案:在body元素上放置onload处理程序,或者如果获取body标记很麻烦(例如,如果您使用母版页),则在视图中运行一些内联​​脚本.
  2. 或:您正在AJAX请求中调用此控制器方法,并希望客户端代码根据返回的内容执行某些操作.根据定义,从JS内部调用AJAX请求,您可以挂钩JS函数以充当响应处理程序,因此可以在控制器方法或视图中构造一些输出来告诉客户端该怎么做,然后编写客户端脚本,以便它会在AJAX响应中查找并执行要求的操作.

  1. You want to run some client-side javascript as soon as the controller method ''returns'', i.e. when the page is served. Answer: put an onload handler on the body element, or run some inline script in the view if getting at the body tag is a pain (i.e. if you''re using a master page.)
  2. Or: You are calling this controller method in an AJAX request, and want the client code to do something as a result of what you return. By definition, an AJAX request is called from within JS and you can hook a JS function to act as a response handler, so construct some output in the controller method or view which tells the client what to do, and write the client script so that it looks in the AJAX response and does whatever it''s asked to.


这篇关于如何从MVC控制器方法调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆