ABP入门系列(5)——展现层实现增删改查

ABP入门系列目录——学习Abp框架之实操演练
源码路径:Github-LearningMpaAbp


这一章节将通过完善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.jsjquery.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,可自行参考。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容