這一章節將通過完善Controller、View、ViewModel,來實現展現層的增刪改查。最終實現效果如下圖:
一、定義Controller
ABP對ASP.NET MVC Controllers進行了集成,通過引入Abp.Web.Mvc命名空間,創建Controller繼承自AbpController, 我們即可使用ABP附加給我們的以下強大功能:
- 本地化
- 異常處理
- 對返回的JsonResult進行包裝
- 審計日志
- 權限認證([AbpMvcAuthorize]特性)
- 工作單元(默認未開啟,通過添加[UnitOfWork]開啟)
1,創建TasksController繼承自AbpController
通過構造函數注入對應用服務的依賴。
[AbpMvcAuthorize]
public class TasksController : AbpController
{
private readonly ITaskAppService _taskAppService;
private readonly IUserAppService _userAppService;
public TasksController(ITaskAppService taskAppService, IUserAppService userAppService)
{
_taskAppService = taskAppService;
_userAppService = userAppService;
}
}
二、創建列表展示分部視圖(_List.cshtml)
在分部視圖中,我們通過循環遍歷,輸出任務清單。
@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>
三,創建新增分部視圖(_CreateTask.cshtml)
為了好的用戶體驗,我們采用異步加載的方式來實現任務的創建。
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,創建分部視圖
其中用到了Bootstrap-Modal,Ajax.BeginForm,對此不了解的可以參考
Ajax.BeginForm()知多少
Bootstrap-Modal的用法介紹
該Partial 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>
對應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);
}
四、創建更新分部視圖(_EditTask.cshtml)
同樣,該視圖也采用異步更新方式,也采用Bootstrap-Modal,Ajax.BeginForm()技術。該Partial 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">
//該段代碼十分重要,確保異步調用后jquery能正確執行驗證邏輯
$(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);
}
五,創建Index視圖
在首頁中,我們一般會用來展示列表,並通過彈出模態框的方式來進行新增更新刪除。為了使用ASP.NET MVC強視圖帶給我們的好處(模型綁定、輸入校驗等等),我們需要創建一個ViewModel來進行模型綁定。因為Abp提倡為每個不同的應用服務提供不同的Dto進行數據交互,新增對應CreateTaskInput,更新對應UpdateTaskInput,展示對應TaskDto。那我們創建的ViewModel就需要包含這幾個模型,方可在一個視圖中完成多個模型的綁定。
1,創建視圖模型(IndexViewModel)
namespace LearningMpaAbp.Web.Models.Tasks
{
public class IndexViewModel
{
/// <summary>
/// 用來進行綁定列表過濾狀態
/// </summary>
public TaskState? SelectedTaskState { get; set; }
/// <summary>
/// 列表展示
/// </summary>
public IReadOnlyList<TaskDto> Tasks { get; }
/// <summary>
/// 創建任務模型
/// </summary>
public CreateTaskInput CreateTaskInput { get; set; }
/// <summary>
/// 更新任務模型
/// </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,創建視圖
Index視圖,通過加載Partial View的形式,將列表、新增視圖一次性加載進來。
@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方式調用Modal進行展現</a>
<!--任務清單按照狀態過濾的下拉框-->
<span class="pull-right">
@Html.DropDownListFor(
model => model.SelectedTaskState,
Model.GetTaskStateSelectListItems(),
new
{
@class = "form-control select2",
id = "TaskStateCombobox"
})
</span>
</h2>
<!--任務清單展示-->
<div class="row" id="taskList">
@{ Html.RenderPartial("_List", Model.Tasks); }
</div>
<!--通過初始加載頁面的時候提前將創建任務模態框加載進來-->
@Html.Action("Create")
<!--編輯任務模態框通過ajax動態填充到此div中-->
<div id="edit">
</div>
<!--Remote方式彈出創建任務模態框-->
<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方式創建任務講解
Remote方式就是,點擊按鈕的時候去加載創建任務的PartialView到指定的div中。而我們代碼中另一種方式是通過@Html.Action("Create")
的方式,在加載Index的視圖的作為子視圖同步加載了進來。
感興趣的同學自行查看源碼,不再講解。
<a class="btn btn-primary" data-toggle="modal" href="@Url.Action("RemoteCreate")" data-target="#modal" role="button">(Create Task)使用Remote方式調用Modal進行展現</a>
<!--Remote方式彈出創建任務模態框-->
<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時,光標顯示在第一個輸入框
$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);
}
//異步開始提交結束后,隱藏遮罩層並清空Form
function hideForm(modalId) {
var $modal = $(modalId);
var $form = $modal.find("form");
abp.ui.clearBusy($modal);
$modal.modal("hide");
//創建成功后,要清空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 + "的任務信息",
function (isConfirmed) {
if (isConfirmed) {
taskService.deleteTask(id)
.done(function () {
abp.notify.info("刪除任務成功!");
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回調函數,以及任務狀態過濾下拉框更新事件,編輯、刪除任務代碼。其中getTaskList()函數是用來異步屬性列表,對應調用的GetList()Action的后台代碼如下:
public PartialViewResult GetList(GetTasksInput input)
{
var output = _taskAppService.GetTasks(input);
return PartialView("_List", output.Tasks);
}
六、總結
至此,完成了任務的增刪改查。展現層主要用到了Asp.net mvc的強類型視圖、Bootstrap-Modal、Ajax異步提交技術。
其中需要注意的是,在異步加載表單時,需要添加以下js代碼,jquery方能進行前端驗證。
<script type="text/javascript">
$(function () {
//allow validation framework to parse DOM
$.validator.unobtrusive.parse('form');
});
</script>
源碼已上傳至Github-LearningMpaAbp,可自行參考。