我在mvc中有动作,当页面请求时触发,并从那里生成我的模型的json并存储在viewbag中。在剃刀视图中,我将json从viewbag存储到角度模型。我的代码假设填充下拉列表但没有得到正确的输出。请告诉我我犯了哪个错误。
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Countries = GetCountries();
return View();
}
public JsonResult GetCountries()
{
List<Country> oList = new List<Country>()
{
new Country {ID=1,Name="United Kingdom"},
new Country {ID=1,Name="United States"},
new Country {ID=1,Name="Italy"},
new Country {ID=1,Name="Germany"},
new Country {ID=1,Name="India"}
};
return Json(oList);
}
}
<div class="row">
<div ng-app="drpdwnApp" ng-controller="drpdwnCtrl">
<select ng-model="ID" ng-options="item.Name for item in CountryList">
<option value="" >--Select--</option>
</select>
</div>
</div>
@section scripts
{
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.CountryList = null;
$scope.fillCountryList = function () {
$scope.CountryList = JSON.parse('@Html.Raw(Json.Encode(ViewBag.Countries))');
};
$scope.fillCountryList();
});
</script>
}
答案 0 :(得分:3)
您可以使用fireTableDataChanged();
服务对服务器端点进行ajax调用,以获取下拉列表的数据。
由于它位于MVC视图中,您应该利用$http
辅助方法为端点构建正确的相对URL。因此,在您的视图文件中,您可以构建到端点的URL并将其传递给您的javascript / angular controller。
Url.Action
现在在角度控制器中,
@section Scripts
{
<script src="~/Scripts/YourAngularControllerFileForThisPage.js"></script>
<script>
var yourApp = yourApp || {};
yourApp.Settings = yourApp.Settings || {};
yourApp.Settings.CountriesUrl= "@Url.Action("GetCountries","YourControllerName")";
angular.module("app").value("appSettings", myApp);
</script>
}
虽然这很好用, 我强烈建议您将此http调用移动到数据服务 并将其注入角度控制器并使用它。
答案 1 :(得分:0)
问题解决了。这是正在运行的代码。
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.CountryList = null;
$scope.fillCountryList = function () {
var raw = @Html.Raw(Json.Encode(ViewBag.Countries));
$scope.CountryList = raw["Data"];
}
$scope.fillCountryList();
});
</script>