[英]Calling Javascript method from Controller in SignalR with MVC 5
[英]Calling method from javascript in MVC
我想从Javascript调用控制器方法。 我使用以下代码:
<input type="submit" name="button" value="Run" onclick="RunEXE"/>
我想编写JavaScript以在控制器中调用以下函数。
public void Run(UserProgram userProgram)
{
SaveAndCompile(userProgram);
}
谁能提供给我JavaScript来调用该函数。
您可以在这里使用Ajax。 jQuery ajax非常灵活和容易
然后
准备要发布的数据
var myData={};// this is similar to your C# class UserProgram structure
myData.property1=value1; //etc
jQuery.ajax{(
url: '/controllerName/Run/', // or '@Url.Action("Run", "ControllerName")'
type: 'post',
data:{userProgram:myData},
success: function (data) { jQuery('#container').html(data); }
)};
或速记
$.post('/controllerName/Run/',{userProgram:myData}, function(result){});
使用JQuery尝试以下操作:
function RunEXE() {
$.post('@Url.Action("Run", "ControllerName")',
{
userProgram: "WhatEver" //The parameter you want to pass to your action
},
function (data) {
//Code for what to do with the result.
})
};
您不能只调用这样的函数。 您需要了解的是javascript在客户端上运行,而函数在服务器上。 您需要做的就是向服务器发出请求,就像加载页面时一样,为此,您需要一个Action
(确保它是POST操作,因为我们将“发布”该请求)。 只需调用所需的函数即可完成此操作:
[HttpPost]
public ActionResult RunAction(string option1)
{
//if needed, you can use the "option1" value to determine the UserProgram to pass
UserProgram userProgram = new UserProgram();
Run(userProgram);
//you can return a JSON reuslt that you can evaluate back at the client
return Json(new { @Success = true, @MyString = "a string" });
}
然后,您想使用ajax从客户端(javascript)调用该函数,为此,我建议使用JQuery,因为它可以简化使用post
:
$.post('@Url.Action("RunAction", "MyController")',
{
option1: "some optional value"
},
function (data) {
alert("success!");
//here you have access to your JSON result via data, for example:
//data.Success = true
//data.MyString = "a string"
}
);
使用普通的AJAX方法如下:
在服务器端(即在Controller中),您正在使用某些类/模型,例如'UserProgram'
我不知道该类中的属性是什么,但是我假设它是:
public class UserProgram
{
public long ID{get;set}
public string Name{get;set}
}
此Model字段应基于您必须传递给AJAX代码的Model,例如:
var myData={ID:1,Name:"RJ"};
$.ajax{(
type: 'post',
url: '/controllerName/Run'
data:{UserProgram:myData},
success: function (data) {
$('#container').empty();
$('#container').html(data);
}
)};
要获得有关使用jQuery在ASP.net MVC中使用ajax调用的完整描述,请参考:
http://bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.