从 MVC 控制器操作调用 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2709978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call javascript from MVC controller action
提问by Jason Marsell
Can I call javascript function from MVC controller action(not from view page) and get return value? How?
我可以从MVC 控制器操作(不是从视图页面)调用 javascript 函数并获取返回值吗?如何?
I need to make request to server from code (.cs)using javascript like here (but this is aspx page)
我需要使用这里的 javascript从代码 (.cs)向服务器发出请求(但这是 aspx 页面)
function getInitData() {
var code; code = 'return {' ;
code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "photo"})[0]';
code += '};'
VK.Api.call('execute', { 'code': code }, onGetInitData);
}
采纳答案by Russ Cam
You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.
您可以从 JavaScript 函数调用控制器操作,但反之则不行。服务器如何知道要定位哪个客户端?服务器只响应请求。
An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.
在发送到客户端的响应中从 JavaScript(使用 jQuery JavaScript 库)调用控制器操作的示例。
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
error : function(req, status, error) {
// do something with error
}
});
回答by Jason Marsell
For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.
对于那些只使用标准表单提交(非 AJAX)的人,还有另一种方法可以在您的操作完成时触发一些 Javascript/JQuery 代码。
First, create a string property on your Model.
首先,在您的模型上创建一个字符串属性。
public class MyModel
{
public string JavascriptToRun { get; set;}
}
Now, bind to your new model property in the Javascript of your view:
现在,在视图的 Javascript 中绑定到新的模型属性:
<script type="text/javascript">
@Model.JavascriptToRun
</script>
Now, also in your view, create a Javascript function that does whatever you need to do:
现在,同样在您看来,创建一个 Javascript 函数来执行您需要执行的任何操作:
<script type="text/javascript">
@Model.JavascriptToRun
function ShowErrorPopup() {
alert('Sorry, we could not process your order.');
}
</script>
Finally, in your controller action, you need to call this new Javascript function:
最后,在您的控制器操作中,您需要调用这个新的 Javascript 函数:
[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
// Do something useful
...
if (success == false)
{
model.JavascriptToRun= "ShowErrorPopup()";
return View(model);
}
else
return RedirectToAction("Success");
}
回答by Dhanasekar
Yes, it is definitely possible using Javascript Result:
是的,绝对可以使用 Javascript 结果:
return JavaScript("Callback()");
Javascript should be referenced by your view:
您的视图应该引用 Javascript:
function Callback(){
// do something where you can call an action method in controller to pass some data via AJAX() request
}
回答by Manpreet Singh Dhillon
It is late answer but can be useful for others. In view use ViewBag as following:
这是迟到的答案,但对其他人有用。在视图中使用 ViewBag 如下:
@Html.Raw("<script>" + ViewBag.DynamicScripts + "</script>")
Then from controller set this ViewBag as follows:
然后从控制器设置这个 ViewBag 如下:
ViewBag.DynamicScripts = "javascriptFun()";
This will execute JavaScript function. But this function would not execute if it is ajax call. To call JavaScript function from ajax call back, return two values from controller and write success function in ajax callback as following:
这将执行 JavaScript 函数。但是这个函数如果是ajax调用就不会执行。要从 ajax 回调调用 JavaScript 函数,从控制器返回两个值并在 ajax 回调中编写成功函数如下:
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
success: function(result, para) {
if(para == 'something'){
//run JavaScript function
}
},
error : function(req, status, error) {
// do something with error
}
});
from controller you can return two values as following:
您可以从控制器返回两个值,如下所示:
return Json(new { json = jr.Data, value2 = "value2" });
回答by Jon Eastwood
There are ways you can mimic this by having your controller return a piece of data, which your view can then translate into a JavaScript call.
您可以通过让控制器返回一段数据来模拟这一点,然后您的视图可以将其转换为 JavaScript 调用。
We do something like this to allow people to use RESTful URLs to share their jquery-rendered workspace view.
我们这样做是为了允许人们使用 RESTful URL 来共享他们的 jquery 呈现的工作区视图。
In our case we pass a list of components which need to be rendered and use Razor to translate these back into jquery calls.
在我们的例子中,我们传递了一个需要渲染的组件列表,并使用 Razor 将它们转换回 jquery 调用。
回答by d.popov
If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt)
So: you can do this by using the .NET's System.Windows.Forms.WebBrowsercontrol to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:
如果我正确理解了这个问题,那么您希望在您的控制器中有一段 JavaScript 代码。(您的问题很清楚,但投票和接受的答案引发了一些疑问)因此:您可以通过使用 .NET 的System.Windows.Forms.WebBrowser控件来执行 javascript 代码以及浏览器可以执行的所有操作来做到这一点。虽然它需要参考 System.Windows.Forms,但交互有点“老派”。例如:
void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
if(search != null)
{
search.SetAttribute("value", "Superman");
foreach(HtmlElement ele in search.Parent.Children)
{
if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
{
ele.InvokeMember("click");
break;
}
}
}
}
So probably nowadays, that would not be the easiest solution.
所以可能现在,这不是最简单的解决方案。
The other option is to use Javascript .NETor jintto run javasctipt, or another solution, based on the specific case.
另一种选择是使用Javascript .NET或jint来运行 javasctipt 或基于特定情况的其他解决方案。
Some related questions on this topic or possible duplicates:
关于这个主题的一些相关问题或可能的重复:
Embedding JavaScript engine into .NET
Load a DOM and Execute javascript, server side, with .Net
使用 .Net 加载 DOM 并在服务器端执行 javascript
Hope this helps.
希望这可以帮助。
回答by Farshad
<script>
$(document).ready(function () {
var msg = '@ViewBag.ErrorMessage'
if (msg.length > 0)
OnFailure('Register', msg);
});
function OnSuccess(header,Message) {
$("#Message_Header").text(header);
$("#Message_Text").text(Message);
$('#MessageDialog').modal('show');
}
function OnFailure(header,error)
{
$("#Message_Header").text(header);
$("#Message_Text").text(error);
$('#MessageDialog').modal('show');
}
</script>
回答by 3Dave
Since your controller actions execute on the server, and JavaScript (usually) executes on the client (browser), this doesn't make sense. If you need some action to happen by default once the page is loaded into the browser, you can use JavaScript's document.OnLoad event handler.
由于您的控制器操作在服务器上执行,而 JavaScript(通常)在客户端(浏览器)上执行,这没有意义。如果您需要在页面加载到浏览器后默认执行某些操作,您可以使用 JavaScript 的 document.OnLoad 事件处理程序。
回答by Sarfraz
The usual/standard way in MVC is that you should put/call your all display, UI, CSS and Javascript in View, however there is no rule to it, you can call it in the Controller as well if you manage to do so (something i don't see the possibility of).
MVC 中通常/标准的方法是,您应该在 View 中放置/调用您的所有显示、UI、CSS 和 Javascript,但是没有规则,如果您设法这样做,您也可以在控制器中调用它(一些我看不到的可能性)。

