我正在尝试将AngularJs与ASP.NET MVC一起使用 - 这是我的第一次尝试。
的index.html
@model string
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container" ng-init="courses = [{'name':'first'},{'name':'second'},{'name':'third'}]">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="course in courses">
<td>{{ course.name }}</td>
</tr>
</tbody>
</table>
_Layout.cshtml
<!DOCTYPE html>
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/angular.min.js"></script>
<title></title>
</head>
<body>
@RenderBody()
</body>
</html>
以上工作正常并且网格显示为名称作为标题,第一,第二和第三作为3行。所以我的下一步是使用
courses = @Html.Raw(Json.Encode(Model))
而不是
courses = [{'name':'first'},{'name':'second'},{'name':'third'}]
CourseController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace AngularJsMvc.Controllers
{
public class CoursesController : Controller
{
// GET: Courses
public ActionResult Index()
{
return View("Index", "", "[{'name':'first'},{'name':'second'}, {'name':'third'}]"); //This works fine when used with @Html.Raw(Model) in index.html
//return View("Index", "", GetCourses()); //This doesn't work when used with with @Html.Raw(Model) in index.html
}
public string GetCourses()
{
var courses = new[]
{
new Course { Name = "First" },
new Course { Name = "Second" },
new Course { Name = "Third" }
};
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
return JsonConvert.SerializeObject(courses, Formatting.None, settings);
}
}
public class Course
{
public string Name { get; set; }
}
}
如果我使用
,这样可以正常工作return View("Index", "", "[{'name':'first'},{'name':'second'},{'name':'third'}]");
但如果我使用
return View("Index", "", GetCourses());
然后,下面是我得到的错误。请帮助 - 我昨天几乎整天都在挣扎。我试过或不使用Json.Encode
angular.min.js:123 Error: [$parse:ueoe]
http://errors.angularjs.org/1.6.4/$parse/ueoe?p0=courses%20%3D
at angular.min.js:6
"<div class="container" ng-init="courses = " [{\"name\":\"first\"},{\"name\":\"second\"},{\"name\":\"third\"}]""="">"
答案 0 :(得分:3)
以下对我有用:
<div class="container" ng-init="courses = @Newtonsoft.Json.JsonConvert.DeserializeObject(Model)">
这也有效:
<div class="container" ng-init="courses = @HttpUtility.HtmlDecode(Model)">
所有关于angular
如何处理它尝试解析的对象以及由于您传递HTML decoded string
它会将其视为字符串,因此它赢得了#{1}}。能够迭代扔掉它。