单击创建视图上的保存按钮后,不会重定向索引视图,也不会刷新索引视图。但数据已成功保存

时间:2016-10-02 20:52:44

标签: c# angularjs asp.net-mvc

在“保存”按钮单击“创建视图”后,屏幕不会重定向到“索引”视图,并且不会刷新数据。但数据已成功保存。如何在保存数据后重定向和刷新索引视图。

的TestController

    using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CRUDMVCAngularJS.Models;

namespace CRUDMVCAngularJS.Controllers
{
    public class TestController : Controller
    {
        private SchoolEntities db = new SchoolEntities();

        // GET: Test
        public ActionResult Index()
        {
            return View();
        }


        // GET: All Students
        public JsonResult GetAllStudent()
        {
            var studentList = db.Students.ToList();
            return Json(studentList, JsonRequestBehavior.AllowGet);
        }


        //GET: Student by Id
        public JsonResult GetStudentById(string id)
        {
            var studentId = Convert.ToInt32(id);
            var getStudentById = db.Students.Find(studentId);
            return Json(getStudentById, JsonRequestBehavior.AllowGet);

        }

        // Add Student
        public string AddStudent(Student student)
        {
            if (student != null)
            {
                using (SchoolEntities contextObj = new SchoolEntities())
                {
                    contextObj.Students.Add(student);
                    contextObj.SaveChanges();
                    return "Student record added successfully";
                }
            }
            else
            {
                return "Invalid student record";
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

索引视图

    @{
        ViewBag.Title = "Index";
    }

    <h2>Index</h2>
    <div ng-controller="mvcCRUDCtrl">
        <p>
            <input type="button" class="btn btn-default" value="Add" ng-click="AddStudentDiv()" />

        </p>
        <div class="divList">
            <p><b><i>Employee List</i></b></p>
            <table class="table table-hover">
                <tr>
                    <td><b>ID</b></td>
                    <td><b>FirstName</b></td>
                    <td><b>LastName</b></td>
                    <td><b>Age</b></td>
                </tr>
                <tr ng-repeat="student in students">
                    <td>
                        {{student.Id}}
                    </td>
                    <td>
                        {{student.FirstName}}
                    </td>
                    <td>
                        {{student.LastName}}
                    </td>
                    <td>
                        {{student.Age}}
                    </td>
                    <td>
                        <span ng-click="editBook(book)" class="btn btn-primary">Edit</span>
                        <span ng-click="deleteBook(book)" class="btn btn-danger">Delete</span>
                    </td>
                </tr>
            </table>
        </div>
    </div>

Create View

<div ng-controller="mvcCRUDCtrl">
    <p class="divHead"></p>
    <table class="table">
        <tr>
            <td><b>FirstName</b></td>
            <td>
                <input type="text" ng-model="FirstName" />
            </td>
        </tr>
        <tr>
            <td><b>LastName</b></td>
            <td>
                <input type="text" ng-model="LastName" />
            </td>
        </tr>
        <tr>
            <td><b>Age</b></td>
            <td>
                <input type="text" ng-model="Age" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="button" class="btn btn-default" value="Save" ng-click="AddUpdateStudent()" />
                <input type="button" class="btn btn-danger" value="Cancel" ng-click="Cancel()" />
            </td>
        </tr>
    </table>
</div>

Layout.cshtml

<!DOCTYPE html>
<html ng-app="mvcCRUDApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Scripts.Render("~/Scripts/angular.min.js")
    @Scripts.Render("~/Scripts/StudentScripts/Module.js")
    @Scripts.Render("~/Scripts/StudentScripts/Controller.js")
    @Scripts.Render("~/Scripts/StudentScripts/Service.js")
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <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 class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

AngularJS模块

var app = angular.module("mvcCRUDApp", []);

AngularJS服务

app.service("crudAJService", function ($http) {

    //get All Students
    this.getStudents = function () {
        return $http.get("../Test/GetAllStudent");
    };

    // get Student by studentId
    this.getStudent = function (studentId) {
        debugger;
        var response = $http({
            method: "post",
            url: "../Test/GetStudentById",
            params: {
                id: JSON.stringify(studentId)
            }
        });
        return response;
    }

    // Add Student
    this.AddStudent = function (student) {
        debugger;
        var response = $http({
            method: "post",
            url: "../Test/AddStudent",
            data: JSON.stringify(student),
            dataType: "json"
        });
        return response;
    }

});

AngularJS控制器

app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {
    GetAllStudents();
    //To Get all student records  
    function GetAllStudents() {
        var getStudentData = crudAJService.getStudents();
        getStudentData.then(function (student) {
            $scope.students = student.data;
        }, function () {
            alert('Error in getting student records');
        });
    }


    $scope.AddUpdateStudent = function () {
        $scope.Action = "Add";
        debugger;
        var Student = {
            FirstName: $scope.FirstName,
            LastName: $scope.LastName,
            Age: $scope.Age
        };
        var getAction = $scope.Action;

        if (getAction == "Update") {
            Student.Id = $scope.Id;
            var getData = crudAJService.updateStudent(Student);
            getData.then(function (msg) {
                GetAllStudents();
                alert(msg.data);
            }, function () {
                alert('Error in updating record');
            });
        } else {
            var getData = crudAJService.AddStudent(Student);
            getData.then(function (msg) {
                GetAllStudents();
                alert(msg.data);
            }, function () {
                alert('Error in adding record');
            });
        }
    }

    $scope.AddStudentDiv = function () {
        ClearFields();
        window.location = "../Test/Create";
    }

    function ClearFields() {
        $scope.Id = "";
        $scope.FirstName = "";
        $scope.LastName = "";
        $scope.Age = "";
    }

    $scope.Cancel = function () {
        window.location = "../Test/Index";
    };
});

2 个答案:

答案 0 :(得分:0)

您是在谈论在添加新学生时双向绑定的视图,是否在成功添加学生之后致电所有学生并重新分配到范围,以便在UI上呈现更改

答案 1 :(得分:0)

要在添加学生记录后重定向,请在window.location = "/Test/Index";AddUpdateStudent成功:

$scope.AddUpdateStudent = function () {
        $scope.Action = "Add";
        debugger;
        var Student = {
            FirstName: $scope.FirstName,
            LastName: $scope.LastName,
            Age: $scope.Age
        };
        var getAction = $scope.Action;

        if (getAction == "Update") {
            Student.Id = $scope.Id;
            var getData = crudAJService.updateStudent(Student);
            getData.then(function (msg) {

                alert(msg.data);
                window.location = "/Test/Index";  // redirect
            }, function () {
                alert('Error in updating record');
            });
        } else {
            var getData = crudAJService.AddStudent(Student);
            getData.then(function (msg) {

                alert(msg.data);
            }, function () {
                alert('Error in adding record');
            });
        }
    }

要显示刷新的学生数据,我认为您需要亲自获取学生数据并通过ng-repeat

绑定它

在索引视图中,我将使用ng-init初始化获取数据:

<div ng-controller="mvcCRUDCtrl" ng-init = "GetAllStudents()">

在控制器中:

app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {

  $scope.GetAllStudents = function() {
        var getStudentData = crudAJService.getStudents();
           getStudentData.then(function (student) {
        $scope.students = student.data;
        }, function () {
           alert('Error in getting student records');
        });
  }