Я получаю следующую ошибку в консоли Chrome, когда пытаюсь перейти на вторую страницу (нажмите «Вставить» с домашней страницы).Я получаю следующее сообщение об ошибке JavaScript: Uncaught Error: [$ injector: modulerr] Не удалось создать экземпляр модуля my -cilbuyer из-за: Ошибка: [$ injector: nomod] Модуль 'my -cilbuyer' недоступен!Вы либо неправильно написали имя модуля, либо забыли загрузить его.При регистрации модуля убедитесь, что вы указали зависимости в качестве второго аргумента.
Я попытался загрузить модуль angular-route.Я полагаю, что мне потребуется модуль маршрутизации, чтобы сделать эту работу.
Home Controller.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Test.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Routing.js
angular.module('MyApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
redirectTo: function () {
return '/home';
}
})
.when('/home', {
templateUrl: '/Index.cshtml',
controller: 'HomeController'
})
.when('/insert', {
templateUrl: '/Insert.cshtml',
controller: 'PencilController'
})
.otherwise({
templateUrl: 'Error.html',
controller: 'ErrorController'
});
});
Controller.js
myapp.controller('pencil-controller', function ($scope, pencilService) {
//Loads all Employee records when page loads
loadPencil();
function loadPencil() {
var PencilRecords = pencilService.getAllPencils();
PencilRecords.then(function (d) {
//success
$scope.Pencil = d.data;
},
function () {
alert("Error occured while fetching pencil list...");
});
}
$scope.save = function () {
var Pencil = {
Name: $scope.Name,
Image: $scope.Image,
Price: $scope.Price,
Description: $scope.Description,
Buyers: $scope.Buyers
};
var saverecords = pencilService.save(Pencil);
saverecords.then(function (d) {
if (d.data.success === true) {
loadPencil();
alert("Pencil added successfully");
$scope.resetSave();
}
else { alert("Pencil not added."); }
},
function () {
alert("Error occurred while adding pencil.");
});
};
//reset controls after save operation
$scope.resetSave = function () {
$scope.Name = '';
$scope.Image = '';
$scope.Price = '';
$scope.Description = '';
$scope.Buyers = '';
};
});
PencilController.cs
using Test.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Test.Controllers
{
public class PencilController : Controller
{
// GET: Pencil
public JsonResult GetPencilHomePage()
{
using (Test db = new TestEntities())
{
List<Pencil> pencils = db.Pencils.ToList();
return Json(pencils, JsonRequestBehavior.AllowGet);
}
}
// POST: Pencil
[HttpPost]
public JsonResult Insert(Pencil pencil)
{
if (pencil != null)
{
using (TestEntities db = new TestEntities())
{
db.Pencils.Add(pencil);
db.SaveChanges();
return Json(new { success = true });
}
}
else
{
return Json(new { success = false });
}
}
public ActionResult Insert()
{
return View();
}
public ActionResult Update()
{
return View();
}
}
}
Index.cshtml
@section scripts{
<script src="~/AngularJSApp/Pencil/Module.js"></script>
<script src="~/AngularJSApp/Pencil/Service.js"></script>
<script src="~/AngularJSApp/Pencil/Controller.js"></script>
}
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<div class="col-6">
Jim
</div>
<div class="col-3">
<!--@Html.ActionLink("Create", "Insert", "Pencil", new { area = "" }, new { @class = "navbar-brand" })-->
<a data-ng-href="@Url.Action("Insert", "Pencil")" target="_self">Insert</a>
</div>
<div class="col-3">
@Html.ActionLink("Update", "Update", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
</div>
<table class="table table-bordered">
<thead style="background-color:lightblue;">
<tr>
<th>Name</th>
<th>Image</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="pencil in Pencils">
<td> {{pencil.Name}}</td>
<td> {{pencil.Image}}</td>
<td>{{pencil.Price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
Insert.cshtml
@{
ViewBag.Title = "Insert";
Layout = "~/Views/Shared/_Layout1.cshtml";
}
<h2>Insert</h2>
<div id="AddNew" ng-controller="pencil-controller">
@*Add New Employee form starts here...*@
<form class="form-horizontal" name="AddNewForm">
<div class="form-group">
<label class="control-label">Name</label>
<input class="form-control"
name="Name" ng-model="Name"
placeholder="" />
</div>
<div class="form-group">
<label class="control-label">Image</label>
<input class="form-control" name="Image"
ng-model="Image" type="text"
placeholder="" />
</div>
<div class="form-group">
<label class="control-label">Price</label>
<input class="form-control" name="Price"
ng-model="Price" type="email" placeholder=""
/>
</div>
<div class="form-group">
<label class="control-label">Description</label>
<input class="form-control" name="Description"
ng-model="Description" type="text"
placeholder="" />
</div>
<div class="form-group">
<label class="control-label"> Designation</label>
</div>
</form>
<button type="button" class="btn btn-primary"
id="btnSave" ng-click="save()">
Save
</button>
<button type="button" class="btn btn-default"
ng-click="resetSave()">
Close
</button>
</div>
@section Scripts{
<script src="~/AngularJSApp/Routing.js"></script>
}
BundleConfig.cs
using System.Web;
using System.Web.Optimization;
namespace Test
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
bundles.Add(new
ScriptBundle("~/bundles/angular").Include(
"~/Scripts/angular.js"));
bundles.Add(new ScriptBundle("~/bundles/angular-
route").Include("~/Scripts/angular-route.js"));
}
}
}
Update.cshtml
@{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Update</h2>
Module.js
var myapp;
(function () {
myapp = angular.module('my-pencilbuyer', []);
})();
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/angular")
@Scripts.Render("~/bundles/angular-route")
</head>
<body ng-app="my-pencilbuyer">
<!--<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
</div>
</div>-->
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
Service.js
myapp.service('pencilService', function ($http) {
this.getAllPencils = function () {
return $http.get("/Pencil/GetPencilHomePage");
};
this.save = function (Pencil) {
var request = $http({
method: 'post',
url: '/Pencil/Insert',
data: Pencil
});
return request;
}
});