ABP入门系列(5)——展现层实现增删改查
ABP入門系列目錄——學(xué)習(xí)Abp框架之實(shí)操演練
源碼路徑:Github-LearningMpaAbp
這一章節(jié)將通過完善Controller、View、ViewModel,來實(shí)現(xiàn)展現(xiàn)層的增刪改查。最終實(shí)現(xiàn)效果如下圖:
展現(xiàn)層最終效果
一、定義Controller
ABP對ASP.NET MVC Controllers進(jìn)行了集成,通過引入Abp.Web.Mvc命名空間,創(chuàng)建Controller繼承自AbpController, 我們即可使用ABP附加給我們的以下強(qiáng)大功能:
- 本地化
- 異常處理
- 對返回的JsonResult進(jìn)行包裝
- 審計日志
- 權(quán)限認(rèn)證([AbpMvcAuthorize]特性)
- 工作單元(默認(rèn)未開啟,通過添加[UnitOfWork]開啟)
1,創(chuàng)建TasksController繼承自AbpController
通過構(gòu)造函數(shù)注入對應(yīng)用服務(wù)的依賴。
?
[AbpMvcAuthorize]public class TasksController : AbpController{private readonly ITaskAppService _taskAppService;private readonly IUserAppService _userAppService;public TasksController(ITaskAppService taskAppService, IUserAppService userAppService){_taskAppService = taskAppService;_userAppService = userAppService;} }二、創(chuàng)建列表展示分部視圖(_List.cshtml)
在分部視圖中,我們通過循環(huán)遍歷,輸出任務(wù)清單。
?
@model IEnumerable<LearningMpaAbp.Tasks.Dtos.TaskDto> <div><ul class="list-group">@foreach (var task in Model){<li class="list-group-item"><div class="btn-group pull-right"><button type="button" class="btn btn-info" onclick="editTask(@task.Id);">Edit</button><button type="button" class="btn btn-success" onclick="deleteTask(@task.Id);">Delete</button></div><div class="media"><a class="media-left" href="#"><i class="fa @task.GetTaskLable() fa-3x"></i></a><div class="media-body"><h4 class="media-heading">@task.Title</h4><p class="text-info">@task.AssignedPersonName</p><span class="text-muted">@task.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")</span></div></div></li>}</ul> </div>列表顯示效果
三,創(chuàng)建新增分部視圖(_CreateTask.cshtml)
為了好的用戶體驗(yàn),我們采用異步加載的方式來實(shí)現(xiàn)任務(wù)的創(chuàng)建。
1,引入js文件
使用異步提交需要引入jquery.validate.unobtrusive.min.js和jquery.unobtrusive-ajax.min.js,其中jquery.unobtrusive-ajax.min.js,需要通過Nuget安裝微軟的Microsoft.jQuery.Unobtrusive.Ajax包獲取。
然后通過捆綁一同引入到視圖中。打開App_Start文件夾下的BundleConfig.cs,添加以下代碼:
?
bundles.Add(new ScriptBundle("~/Bundles/unobtrusive/js").Include("~/Scripts/jquery.validate.unobtrusive.min.js","~/Scripts/jquery.unobtrusive-ajax.min.js"));找到Views/Shared/_Layout.cshtml,添加對捆綁的js引用。
?
@Scripts.Render("~/Bundles/vendor/js/bottom") @Scripts.Render("~/Bundles/js") //在此處添加下面一行代碼 @Scripts.Render("~/Bundles/unobtrusive/js")2,創(chuàng)建分部視圖
其中用到了Bootstrap-Modal,Ajax.BeginForm,對此不了解的可以參考
Ajax.BeginForm()知多少
Bootstrap-Modal的用法介紹
該P(yáng)artial View綁定CreateTaskInput模型。最終_CreateTask.cshtml代碼如下:
?
@model LearningMpaAbp.Tasks.Dtos.CreateTaskInput@{ViewBag.Title = "Create"; } <div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="createTask" data-backdrop="static"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><h4 class="modal-title" id="myModalLabel">Create Task</h4></div><div class="modal-body" id="modalContent">@using (Ajax.BeginForm("Create", "Tasks", new AjaxOptions(){UpdateTargetId = "taskList",InsertionMode = InsertionMode.Replace,OnBegin = "beginPost('#add')",OnSuccess = "hideForm('#add')",OnFailure = "errorPost(xhr, status, error,'#add')"})){@Html.AntiForgeryToken()<div class="form-horizontal"><h4>Task</h4><hr />@Html.ValidationSummary(true, "", new { @class = "text-danger" })<div class="form-group">@Html.LabelFor(model => model.AssignedPersonId, "AssignedPersonId", htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.DropDownList("AssignedPersonId", null, htmlAttributes: new { @class = "form-control" })@Html.ValidationMessageFor(model => model.AssignedPersonId, "", new { @class = "text-danger" })</div></div><div class="form-group">@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })</div></div><div class="form-group">@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })</div></div><div class="form-group">@Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EnumDropDownListFor(model => model.State, htmlAttributes: new { @class = "form-control" })@Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })</div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><button type="submit" class="btn btn-default">Create</button></div></div></div>}</div></div></div> </div>對應(yīng)Controller代碼:
?
[ChildActionOnly] public PartialViewResult Create() {var userList = _userAppService.GetUsers();ViewBag.AssignedPersonId = new SelectList(userList.Items, "Id", "Name");return PartialView("_CreateTask"); }[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(CreateTaskInput task) {var id = _taskAppService.CreateTask(task);var input = new GetTasksInput();var output = _taskAppService.GetTasks(input);return PartialView("_List", output.Tasks); }四、創(chuàng)建更新分部視圖(_EditTask.cshtml)
同樣,該視圖也采用異步更新方式,也采用Bootstrap-Modal,Ajax.BeginForm()技術(shù)。該P(yáng)artial View綁定UpdateTaskInput模型。
?
@model LearningMpaAbp.Tasks.Dtos.UpdateTaskInput @{ViewBag.Title = "Edit"; }<div class="modal fade" id="editTask" tabindex="-1" role="dialog" aria-labelledby="editTask" data-backdrop="static"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><h4 class="modal-title" id="myModalLabel">Edit Task</h4></div><div class="modal-body" id="modalContent">@using (Ajax.BeginForm("Edit", "Tasks", new AjaxOptions(){UpdateTargetId = "taskList",InsertionMode = InsertionMode.Replace,OnBegin = "beginPost('#editTask')",OnSuccess = "hideForm('#editTask')"})){@Html.AntiForgeryToken()<div class="form-horizontal"><h4>Task</h4><hr />@Html.ValidationSummary(true, "", new { @class = "text-danger" })@Html.HiddenFor(model => model.Id)<div class="form-group">@Html.LabelFor(model => model.AssignedPersonId, "AssignedPersonId", htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.DropDownList("AssignedPersonId", null, htmlAttributes: new { @class = "form-control" })@Html.ValidationMessageFor(model => model.AssignedPersonId, "", new { @class = "text-danger" })</div></div><div class="form-group">@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })</div></div><div class="form-group">@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })</div></div><div class="form-group">@Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EnumDropDownListFor(model => model.State, htmlAttributes: new { @class = "form-control" })@Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })</div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Save" class="btn btn-default" /></div></div></div>}</div></div></div> </div> <script type="text/javascript">//該段代碼十分重要,確保異步調(diào)用后jquery能正確執(zhí)行驗(yàn)證邏輯$(function () {//allow validation framework to parse DOM$.validator.unobtrusive.parse('form');}); </script>后臺代碼:
?
public PartialViewResult Edit(int id) {var task = _taskAppService.GetTaskById(id);var updateTaskDto = AutoMapper.Mapper.Map<UpdateTaskInput>(task);var userList = _userAppService.GetUsers();ViewBag.AssignedPersonId = new SelectList(userList.Items, "Id", "Name", updateTaskDto.AssignedPersonId);return PartialView("_EditTask", updateTaskDto); }[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(UpdateTaskInput updateTaskDto) {_taskAppService.UpdateTask(updateTaskDto);var input = new GetTasksInput();var output = _taskAppService.GetTasks(input);return PartialView("_List", output.Tasks); }五,創(chuàng)建Index視圖
在首頁中,我們一般會用來展示列表,并通過彈出模態(tài)框的方式來進(jìn)行新增更新刪除。為了使用ASP.NET MVC強(qiáng)視圖帶給我們的好處(模型綁定、輸入校驗(yàn)等等),我們需要創(chuàng)建一個ViewModel來進(jìn)行模型綁定。因?yàn)锳bp提倡為每個不同的應(yīng)用服務(wù)提供不同的Dto進(jìn)行數(shù)據(jù)交互,新增對應(yīng)CreateTaskInput,更新對應(yīng)UpdateTaskInput,展示對應(yīng)TaskDto。那我們創(chuàng)建的ViewModel就需要包含這幾個模型,方可在一個視圖中完成多個模型的綁定。
1,創(chuàng)建視圖模型(IndexViewModel)
?
namespace LearningMpaAbp.Web.Models.Tasks {public class IndexViewModel{/// <summary>/// 用來進(jìn)行綁定列表過濾狀態(tài)/// </summary>public TaskState? SelectedTaskState { get; set; }/// <summary>/// 列表展示/// </summary>public IReadOnlyList<TaskDto> Tasks { get; }/// <summary>/// 創(chuàng)建任務(wù)模型/// </summary>public CreateTaskInput CreateTaskInput { get; set; }/// <summary>/// 更新任務(wù)模型/// </summary>public UpdateTaskInput UpdateTaskInput { get; set; }public IndexViewModel(IReadOnlyList<TaskDto> items){Tasks = items;}/// <summary>/// 用于過濾下拉框的綁定/// </summary>/// <returns></returns>public List<SelectListItem> GetTaskStateSelectListItems(){var list=new List<SelectListItem>(){new SelectListItem(){Text = "AllTasks",Value = "",Selected = SelectedTaskState==null}};list.AddRange(Enum.GetValues(typeof(TaskState)).Cast<TaskState>().Select(state=>new SelectListItem(){Text = $"TaskState_{state}",Value = state.ToString(),Selected = state==SelectedTaskState}));return list;}} }2,創(chuàng)建視圖
Index視圖,通過加載Partial View的形式,將列表、新增視圖一次性加載進(jìn)來。
?
@using Abp.Web.Mvc.Extensions @model LearningMpaAbp.Web.Models.Tasks.IndexViewModel@{ViewBag.Title = L("TaskList");ViewBag.ActiveMenu = "TaskList"; //Matches with the menu name in SimpleTaskAppNavigationProvider to highlight the menu item } @section scripts{@Html.IncludeScript("~/Views/Tasks/index.js"); } <h2>@L("TaskList")<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#add">Create Task</button><a class="btn btn-primary" data-toggle="modal" href="@Url.Action("RemoteCreate")" data-target="#modal" role="button">(Create Task)使用Remote方式調(diào)用Modal進(jìn)行展現(xiàn)</a><!--任務(wù)清單按照狀態(tài)過濾的下拉框--><span class="pull-right">@Html.DropDownListFor(model => model.SelectedTaskState,Model.GetTaskStateSelectListItems(),new{@class = "form-control select2",id = "TaskStateCombobox"})</span> </h2><!--任務(wù)清單展示--> <div class="row" id="taskList">@{ Html.RenderPartial("_List", Model.Tasks); } </div><!--通過初始加載頁面的時候提前將創(chuàng)建任務(wù)模態(tài)框加載進(jìn)來--> @Html.Action("Create")<!--編輯任務(wù)模態(tài)框通過ajax動態(tài)填充到此div中--> <div id="edit"></div><!--Remote方式彈出創(chuàng)建任務(wù)模態(tài)框--> <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="createTask" data-backdrop="static"><div class="modal-dialog" role="document"><div class="modal-content"></div></div> </div>3,Remote方式創(chuàng)建任務(wù)講解
Remote方式就是,點(diǎn)擊按鈕的時候去加載創(chuàng)建任務(wù)的PartialView到指定的div中。而我們代碼中另一種方式是通過@Html.Action("Create")的方式,在加載Index的視圖的作為子視圖同步加載了進(jìn)來。
感興趣的同學(xué)自行查看源碼,不再講解。
?
<a class="btn btn-primary" data-toggle="modal" href="@Url.Action("RemoteCreate")" data-target="#modal" role="button">(Create Task)使用Remote方式調(diào)用Modal進(jìn)行展現(xiàn)</a><!--Remote方式彈出創(chuàng)建任務(wù)模態(tài)框--> <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="createTask" data-backdrop="static"><div class="modal-dialog" role="document"><div class="modal-content"></div></div> </div>4,后臺代碼
?
public ActionResult Index(GetTasksInput input){var output = _taskAppService.GetTasks(input);var model = new IndexViewModel(output.Tasks){SelectedTaskState = input.State};return View(model);}5,js代碼(index.js)
?
var taskService = abp.services.app.task;(function ($) {$(function () {var $taskStateCombobox = $('#TaskStateCombobox');$taskStateCombobox.change(function () {getTaskList();});var $modal = $(".modal");//顯示modal時,光標(biāo)顯示在第一個輸入框$modal.on('shown.bs.modal',function () {$modal.find('input:not([type=hidden]):first').focus();});}); })(jQuery);//異步開始提交時,顯示遮罩層 function beginPost(modalId) {var $modal = $(modalId);abp.ui.setBusy($modal); }//異步開始提交結(jié)束后,隱藏遮罩層并清空Form function hideForm(modalId) {var $modal = $(modalId);var $form = $modal.find("form");abp.ui.clearBusy($modal);$modal.modal("hide");//創(chuàng)建成功后,要清空form表單$form[0].reset(); }//處理異步提交異常 function errorPost(xhr, status, error, modalId) {if (error.length>0) {abp.notify.error('Something is going wrong, please retry again later!');var $modal = $(modalId);abp.ui.clearBusy($modal);} }function editTask(id) {abp.ajax({url: "/tasks/edit",data: { "id": id },type: "GET",dataType: "html"}).done(function (data) {$("#edit").html(data);$("#editTask").modal("show");}).fail(function (data) {abp.notify.error('Something is wrong!');}); }function deleteTask(id) {abp.message.confirm("是否刪除Id為" + id + "的任務(wù)信息",function (isConfirmed) {if (isConfirmed) {taskService.deleteTask(id).done(function () {abp.notify.info("刪除任務(wù)成功!");getTaskList();});}});}function getTaskList() {var $taskStateCombobox = $('#TaskStateCombobox');var url = '/Tasks/GetList?state=' + $taskStateCombobox.val();abp.ajax({url: url,type: "GET",dataType: "html"}).done(function (data) {$("#taskList").html(data);}); }js代碼中處理了Ajax回調(diào)函數(shù),以及任務(wù)狀態(tài)過濾下拉框更新事件,編輯、刪除任務(wù)代碼。其中g(shù)etTaskList()函數(shù)是用來異步刷新列表,對應(yīng)調(diào)用的GetList()Action的后臺代碼如下:
?
public PartialViewResult GetList(GetTasksInput input) {var output = _taskAppService.GetTasks(input);return PartialView("_List", output.Tasks); }六、總結(jié)
至此,完成了任務(wù)的增刪改查。展現(xiàn)層主要用到了Asp.net mvc的強(qiáng)類型視圖、Bootstrap-Modal、Ajax異步提交技術(shù)。
其中需要注意的是,在異步加載表單時,需要添加以下js代碼,jquery方能進(jìn)行前端驗(yàn)證。
?
<script type="text/javascript">$(function () {//allow validation framework to parse DOM$.validator.unobtrusive.parse('form');}); </script>源碼已上傳至Github-LearningMpaAbp,可自行參考。
作者:圣杰
鏈接:https://www.jianshu.com/p/620c20fa511b
來源:簡書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
總結(jié)
以上是生活随笔為你收集整理的ABP入门系列(5)——展现层实现增删改查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7年了!IE终于死透了
- 下一篇: Sites Table