gpt4 book ai didi

c# - Angular asp.net mvc 调用 c# Controller 函数

转载 作者:行者123 更新时间:2023-11-30 20:34:38 24 4
gpt4 key购买 nike

我尝试了很多东西,这是我目前所拥有的:

所以我尝试从我的 javascript 中调用这个方法“runTest()”。该方法实际上并没有通过,它成功通过了,所以“handleTest()”通过了并且也成功了。我需要它来实际调用 Controller 函数。

Javascript/Angular/JQuery

$scope.runTest = function (myTest) {
$.ajax({
method: 'POST',
Url: 'Tests/runTest',
contentType: 'application/json;',
data: myTest,
success: function () { handleTest(myTest); },
error: function () { alert('no object found'); }
});
}

function handleTest(currentTest){
var updated = { id: currentTest.id, name: currentTest.name, schedule: currentTest.schedule, description: currentTest.description, server: currentTest.server, port: currentTest.port, method: currentTest.method };
//var updated = currentTest;
$http({
method: "PUT",
url: 'http://~~api address~~/api/tests/' + (currentTest.id),
data: updated
})
.success(function (data, status, headers) {
alert("Test was successfully updated.");
$state.reload();
})
.error(function (data, status, headers) {
alert("Test could not be updated.");
$state.reload();
});
}

C# Controller 方法(名为 TestsController)

[HttpPost]
public ActionResult runTest(StandardTest myTest)
{
myTest.lastResult = MyEnum.Pass;
log.Info(myTest.name + " " + myTest.lastResult + " " + myTest.id);
return Json(myTest, JsonRequestBehavior.AllowGet);
}

如有任何帮助,我们将不胜感激。

最佳答案

例子如下:

在你的 C# Controller 中

[HttpPost]
public ActionResult runTest(StandardTest myTest)
{
myTest.lastResult = MyEnum.Pass;
log.Info(myTest.name + " " + myTest.lastResult + " " + myTest.id);

if (!testPassed){
//test did not pass
return Json(new {success = false,
responseText = "Test did not pass",JsonRequestBehavior.AllowGet);
}
else
{
//Test Passed
return Json(new {success = true,
responseText= "Test Passed"},JsonRequestBehavior.AllowGet);
}
}

尝试使用 Angular $http 服务运行您的网络请求。

 angular.module('YourModuleName')
.controller("ngControllerName", ["$http", "$scope", function ($http, $scope) {
/*Request to C# Controller*/
$scope.runTest = function(myTest){
var config = {
params:{myTest: myTest}
}
$http.get('/Tests/runTest', config).success(function (data) {
if(data !=null && data.success){
handleTest(myTest);
}
}).error(function (error) {
//Handle Error
});
}
}

关于c# - Angular asp.net mvc 调用 c# Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38881663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com