使用ASP的单页应用程序。NET MVC和jQuery的CRUD方法

介绍 在本文中,我将告诉您如何使用ASP创建单个页面应用程序。NET MVC和jQuery。如果不使用Angular、React和其他第三方的JavaScripts,是很难实现SPA的。在这篇文章中,我将只解释控制器和UI级的交互。我跳过了数据访问层。如果您需要,请下载附件,其中包括应用程序的整体代码。 注意:我对CRUD操作使用了代码优先的方法。下载项目文件后,恢复包并更改连接字符串web。配置并在包管理器控制台中运行update-database命令。 背景 所需内容 ASP。NET mvc jquery sammy . js(用于路由) 使用的代码 创建一个新的MVC项目。 在布局页面中添加jQuery和Sammy.js引用。添加div标记(MainContent),在其中呈现所有的部分视图。 隐藏,复制Code

  
      
      
    @ViewBag.Title - My ASP.NET Application  
    @Styles.Render("~/Content/css")  
    @Scripts.Render("~/bundles/modernizr")  
      
      
  

在您的项目中创建layout-routing.js文件,该文件包含应用程序的路由结构,如下所示。 隐藏,收缩,复制Code

var mainContent;  
var titleContent;  
  
$(function () {  
    mainContent = $("#MainContent"); /// render partial views.  
    titleContent = $("title"); // render titles.  
});  
  
var routingApp = $.sammy("#MainContent", function () {  
    this.get("#/Student/Index", function (context) {  
        titleContent.html("Student Page");  
        $.get("/Student/Index", function (data) {  
            context.$element().html(data);  
        });  
    });  
  
    this.get("#/Student/Add", function (context) {  
        titleContent.html("Add Student");  
        //$("#BigLoader").modal('show'); // If you want to show loader  
        $.get("/Student/Add", function (data) {  
            //$("#BigLoader").modal('hide');  
            context.$element().html(data);  
        });  
    });  
  
    this.get("#/Student/Edit", function (context) {  
        titleContent.html("Edit Student");  
        $.get("/Student/Edit", {  
            studentID: context.params.id // pass student id  
        }, function (data) {  
            context.$element().html(data);  
        });  
    });  
  
    this.get("#/Home/About", function (context) {  
        titleContent.html("About");  
        $.get("/Home/About", function (data) {  
            context.$element().html(data);  
        });  
    });  
  
    this.get("#/Home/Contact", function (context) {  
        titleContent.html("Contact");  
        $.get("/Home/Contact", function (data) {  
            context.$element().html(data);  
        });  
    });  
});  
  
$(function () {  
    routingApp.run("#/Student/Index"); // default routing page.  
});  
  
function IfLinkNotExist(type, path) {  
    if (!(type != null && path != null))  
        return false;  
  
    var isExist = true;  
  
    if (type.toLowerCase() == "get") {  
        if (routingApp.routes.get != undefined) {  
            $.map(routingApp.routes.get, function (item) {  
                if (item.path.toString().replace("/#", "#").replace(/\\/g, '').replace("$/", "").indexOf(path) >= 0) {  
                    isExist = false;  
                }  
            });  
        }  
    } else if (type.toLowerCase() == "post") {  
        if (routingApp.routes.post != undefined) {  
            $.map(routingApp.routes.post, function (item) {  
                if (item.path.toString().replace("/#", "#").replace(/\\/g, '').replace("$/", "").indexOf(path) >= 0) {  
                    isExist = false;  
                }  
            });  
        }  
    }  
    return isExist;  
}  

IfLinkNotExist()检查url是否不应该重复,之后我们将添加动态url在页面加载的路由列表。 在_layout中添加布局路由引用。cshtml页面。 隐藏,复制Code

  
    @*@Scripts.Render("~/bundles/jquery")*@  
    @Scripts.Render("~/bundles/bootstrap")  
    @RenderSection("scripts", required: false)  

添加一个新的控制器“WelcomeController”,它只有一个动作“Index”。 隐藏,复制Code

namespace MvcSpaDemo.Controllers  
{  
    public class WelcomeController : Controller  
    {  
        public ActionResult Index()  
        {  
            return View();  
        }  
    }  
}

使用右键单击创建“Index”操作的视图。 在该视图中,附加布局页面链接。(我们需要为第一次渲染布局页面)。 隐藏,复制Code

@{  
    ViewBag.Title = "Index";  
    Layout = "~/Views/Shared/_Layout.cshtml";  
}  
  

Welcome

现在,创建student Controller,其中包括student CRUD操作模块。(添加、更新、删除、查看)。 观点的学生 隐藏,复制Code

public ActionResult Index()  
 {  
     return PartialView();  
 }  
  
 public ActionResult _Index()  
 {  
     var students = StudentData.GetStudents();  
     return PartialView(students);  
  } 

添加两个没有布局页面的视图。一个用于外部学生内容,如标题、添加按钮等,另一个用于学生表。 Index.cshtml  隐藏,收缩,复制Code

@{  
    Layout = null;  
}  
  

Students

_Index.cshtml 隐藏,收缩,复制Code

@model IEnumerable  
@{  
    Layout = null;  
}  
  
  
        @foreach (var item in Model)  
        {  
              
        }  
    
ID Name Email Class Action
@item.StudentID @item.FirstName @item.LastName @item.Email @item.Class Edit Delete

更改RouteConfig.cs中的默认控制器和动作。 隐藏,复制Code

public class RouteConfig  
    {  
        public static void RegisterRoutes(RouteCollection routes)  
        {  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  
            routes.MapRoute(  
                name: "Default",  
                url: "{controller}/{action}/{id}",  
                defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional }  
            );  
        }  
    }  

使用F5运行应用程序。对About和Contact页面也执行相同的路由。 添加学生asd  现在,在Controller中添加“Create Student Actions”。 隐藏,复制Code

public ActionResult Add()  
        {  
            var student = new Student();  
            ViewBag.Status = "Add";  
            return PartialView(student);  
        }  
  
        [HttpPost]  
        public ActionResult Create(Student student)  
        {  
            StudentData.AddStudent(student);  
            return Json(true, JsonRequestBehavior.AllowGet);  
        }  

我们将使用创建或更新的动态路由脚本添加添加页面。 隐藏,收缩,复制Code

@model MvcSpaDemo.Entities.Student  
@{  
    ViewBag.Title = "Add";  
    Layout = null;  
  
    // We use same page for add and edit.  
    var urlPostString = "/Student/Create";  
    if (ViewBag.Status == "Edit")  
    {  
        urlPostString = "/Student/Update";  
    }  
}  
  

@ViewBag.Status Student

@Html.HiddenFor(x => x.StudentID)
@Html.TextBoxFor(x => x.FirstName, new { @class = "form-control square" })
@Html.TextBoxFor(x => x.LastName, new { @class = "form-control square" })
@Html.TextBoxFor(x => x.Email, new { @class = "form-control square" })
@Html.TextBoxFor(x => x.Class, new { @class = "form-control square" })

现在,运行应用程序。 编辑学生 现在,继续编辑模块。在控制器中添加编辑动作。 隐藏,复制Code

public ActionResult Edit(int studentID) // studentID nothing but parameter name which we pass in layout-routing.  
        {  
            var student = StudentData.GetStudentById(studentID);  
            ViewBag.Status = "Edit";  
            return PartialView("Add", student);  
        }  
  
        [HttpPost]  
        public ActionResult Update(Student student)  
        {  
            StudentData.UpdateStudent(student);  
            return Json(true, JsonRequestBehavior.AllowGet);  
        }  

我们使用相同的部分视图进行添加和编辑,所以这里不需要为edit. 创建一个新的视图。 添加操作方法后,只需运行应用程序。 删除Student  现在,我们将实现删除操作。 我们已经在Student Index.cshtml中编写了删除按钮的代码。 隐藏,复制Code

function GetStudents() {  
        $.get("/Student/_Index/", function (data) {  
            $("#StudentDiv").html(data);  
        });  
    }  
  
    function DeleteStudent(studentID) {  
        if (confirm("Delete student?")) {  
            $.get("/Student/Delete/", { studentID: studentID }, function (data) {  
                GetStudents();  
            });  
        }  
    }  

运行应用程序。 我希望您喜欢这篇文章。欢迎您对本文提出宝贵的反馈、问题或评论。 本文转载于:http://www.diyabc.com/frontweb/news15850.html

你可能感兴趣的:(使用ASP的单页应用程序。NET MVC和jQuery的CRUD方法)