簡體   English   中英

角ASP.NET MVC調用C#控制器函數

[英]Angular asp.net mvc calling c# controller function

我嘗試了一堆東西,這就是我到目前為止所擁有的:

因此,我嘗試從我的JavaScript中將此方法稱為“ runTest()”。 該方法實際上並沒有成功,而是成功通過,因此“ handleTest()”也成功了。 我需要它來實際調用控制器功能。

使用Javascript /角/ 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#控制器方法 (名為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#控制器中

[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);
     }   
}

嘗試使用有角的$ http服務運行您的Web請求。

 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 
           });
         }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM