2016-05-06 141 views
0

我從視圖傳遞網址到控制器$http.Post如何將URL從視圖傳遞給Angularjs控制器文件?

視圖(Asp.net MVC視圖)

<form name="form" ng-controller="LoginController" > 
    <div id="dvContainer" ng-init="Url= @Url.Action("VerifyLogin", "Visitor")"> 
     <span ng-model="Message" class="text-danger"></span> 
     <table> 
      <tr> 
       <td>UserName</td> 
       <td> 
        <input name="txtUser" type="text" required ng-model="UserName" /> 
        <span ng-show="(form.txtUser.$dirty || submitted) && 
           form.txtUser.$error.required">UserName is required.</span> 
       </td> 
      </tr> 
      <tr> 
       <td>Password</td> 
       <td><input type="password" required ng-model="Password" /></td> 
      </tr> 
      <tr> 
       <td colspan="2"><button type="submit" ng-click="submit($event)">Login</button></td> 
      </tr> 
     </table> 

    </div> 
</form> 

在我的控制器(Angularjs控制器)

var app = angular.module('VisitorApp', []); 

//AngularJS controller 
app.controller('LoginController', function ($scope, $http) { 
    $scope.submit = function() { 
     alert('hi') 
     // Set the 'submitted' flag to true 
     alert($scope.UserName); 
     alert($scope.Password); 
     var loginModel = { 
      UserName: $scope.UserName, 
      PassWord:$scope.Password 
     }; 

     $http.post($scope.Url, loginModel).success(function (data) { 
      $scope.Message = data.Message; 
     }).error(function (data) { 
      $scope.error = "An error has occured while adding! " + data; 
     }); 
    }; 
}); 

我試圖訪問正在使用NG-初始化定義的URL。該應用程序正在拋出錯誤

[$parse:syntax] Syntax Error: Token '/' not a primary expression at column 6 of the expression [Url= /Visitor/VerifyLogin] starting at [/Visitor/VerifyLogin]. 

我是Angularjs的新手,所以無法弄清楚我做錯了什麼。

+0

也許有一個額外的/在開始或結束? –

+0

「$ scope.Url」在哪裏/如何定義? – Kyle

+0

@KKKKKKKK它在這裏定義ng-init =「Url = @ Url.Action(」VerifyLogin「,」Visitor「)」 – ankur

回答

2

您可以使用角度值提供程序將此URL(或其他任何東西)從您的視圖傳遞到角度控制器。

只需創建一個JavaScript對象並創建Url屬性並設置其值並使用值提供程序傳遞此對象。

@section Scripts 
{ 
    <script src="~/Scripts/YourAngularControllerFileForThisPage.js"></script> 
    <script> 
     var myApp = myApp || {}; 
     myApp.Settings = myApp.Settings || {}; 
     myApp.Settings.Url= "@Url.Action("VerifyLogin","Visitor")"; 
     angular.module("app").value("appSettings", myApp); 
    </script> 
} 

現在在你的控制器,只需在使用AppSettings對象

var app = angular.module("app", []); 
app.controller('ctrl', ['$scope', 'appSettings', function ($scope, appSettings) { 
    $scope.URL = 'nothing'; 
    $scope.greeting = 'Hola!'; 
    console.log('Url ', appSettings.Settings.Url); 
    // You can use appSettings.Settings.Url for your ajax calls now 
}]); 
0

我已經遇到同樣的問題,並沒有想用價值的Url.Action傳遞給我的控制器。我發現在Url.Action的返回值的開始和結尾添加撇號可解決問題。我結束了寫這個擴展來幫助我:

public static MvcHtmlString ActionString(this UrlHelper url, string action, string controller, object routeValues) 
    { 
     return MvcHtmlString.Create("'" + url.Action(action, controller, routeValues) + "'"); 
    } 
相關問題