![](/img/trans.png)
[英]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.