中国建设监理协会网站,电子商务网站建设论文开题报告,wordpress wpadmin修改,百度seo查询ABP入门系列目录——学习Abp框架之实操演练源码路径#xff1a;Github-LearningMpaAbp 这一章节将通过完善Controller、View、ViewModel#xff0c;来实现展现层的增删改查。最终实现效果如下图#xff1a; 展现层最终效果
一、定义Controller
ABP对ASP.NET MVC Controlle… 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 IEnumerableLearningMpaAbp.Tasks.Dtos.TaskDto
divul classlist-groupforeach (var task in Model){li classlist-group-itemdiv classbtn-group pull-rightbutton typebutton classbtn btn-info onclickeditTask(task.Id);Edit/buttonbutton typebutton classbtn btn-success onclickdeleteTask(task.Id);Delete/button/divdiv classmediaa classmedia-left href#i classfa task.GetTaskLable() fa-3x/i/adiv classmedia-bodyh4 classmedia-headingtask.Title/h4p classtext-infotask.AssignedPersonName/pspan classtext-mutedtask.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-ModalAjax.BeginForm对此不了解的可以参考Ajax.BeginForm()知多少Bootstrap-Modal的用法介绍
该Partial View绑定CreateTaskInput模型。最终_CreateTask.cshtml代码如下 model LearningMpaAbp.Tasks.Dtos.CreateTaskInput{ViewBag.Title Create;
}
div classmodal fade idadd tabindex-1 roledialog aria-labelledbycreateTask data-backdropstaticdiv classmodal-dialog roledocumentdiv classmodal-contentdiv classmodal-headerbutton typebutton classclose data-dismissmodalspan aria-hiddentrue×/spanspan classsr-onlyClose/span/buttonh4 classmodal-title idmyModalLabelCreate Task/h4/divdiv classmodal-body idmodalContentusing (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 classform-horizontalh4Task/h4hr /Html.ValidationSummary(true, , new { class text-danger })div classform-groupHtml.LabelFor(model model.AssignedPersonId, AssignedPersonId, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.DropDownList(AssignedPersonId, null, htmlAttributes: new { class form-control })Html.ValidationMessageFor(model model.AssignedPersonId, , new { class text-danger })/div/divdiv classform-groupHtml.LabelFor(model model.Title, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.EditorFor(model model.Title, new { htmlAttributes new { class form-control } })Html.ValidationMessageFor(model model.Title, , new { class text-danger })/div/divdiv classform-groupHtml.LabelFor(model model.Description, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.EditorFor(model model.Description, new { htmlAttributes new { class form-control } })Html.ValidationMessageFor(model model.Description, , new { class text-danger })/div/divdiv classform-groupHtml.LabelFor(model model.State, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.EnumDropDownListFor(model model.State, htmlAttributes: new { class form-control })Html.ValidationMessageFor(model model.State, , new { class text-danger })/div/divdiv classform-groupdiv classcol-md-offset-2 col-md-10button typesubmit classbtn btn-defaultCreate/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-ModalAjax.BeginForm()技术。该Partial View绑定UpdateTaskInput模型。 model LearningMpaAbp.Tasks.Dtos.UpdateTaskInput
{ViewBag.Title Edit;
}div classmodal fade ideditTask tabindex-1 roledialog aria-labelledbyeditTask data-backdropstaticdiv classmodal-dialog roledocumentdiv classmodal-contentdiv classmodal-headerbutton typebutton classclose data-dismissmodalspan aria-hiddentrue×/spanspan classsr-onlyClose/span/buttonh4 classmodal-title idmyModalLabelEdit Task/h4/divdiv classmodal-body idmodalContentusing (Ajax.BeginForm(Edit, Tasks, new AjaxOptions(){UpdateTargetId taskList,InsertionMode InsertionMode.Replace,OnBegin beginPost(#editTask),OnSuccess hideForm(#editTask)})){Html.AntiForgeryToken()div classform-horizontalh4Task/h4hr /Html.ValidationSummary(true, , new { class text-danger })Html.HiddenFor(model model.Id)div classform-groupHtml.LabelFor(model model.AssignedPersonId, AssignedPersonId, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.DropDownList(AssignedPersonId, null, htmlAttributes: new { class form-control })Html.ValidationMessageFor(model model.AssignedPersonId, , new { class text-danger })/div/divdiv classform-groupHtml.LabelFor(model model.Title, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.EditorFor(model model.Title, new { htmlAttributes new { class form-control } })Html.ValidationMessageFor(model model.Title, , new { class text-danger })/div/divdiv classform-groupHtml.LabelFor(model model.Description, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.EditorFor(model model.Description, new { htmlAttributes new { class form-control } })Html.ValidationMessageFor(model model.Description, , new { class text-danger })/div/divdiv classform-groupHtml.LabelFor(model model.State, htmlAttributes: new { class control-label col-md-2 })div classcol-md-10Html.EnumDropDownListFor(model model.State, htmlAttributes: new { class form-control })Html.ValidationMessageFor(model model.State, , new { class text-danger })/div/divdiv classform-groupdiv classcol-md-offset-2 col-md-10input typesubmit valueSave classbtn btn-default //div/div/div}/div/div/div
/div
script typetext/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.MapUpdateTaskInput(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/// 用来进行绑定列表过滤状态/// /summarypublic TaskState? SelectedTaskState { get; set; }/// summary/// 列表展示/// /summarypublic IReadOnlyListTaskDto Tasks { get; }/// summary/// 创建任务模型/// /summarypublic CreateTaskInput CreateTaskInput { get; set; }/// summary/// 更新任务模型/// /summarypublic UpdateTaskInput UpdateTaskInput { get; set; }public IndexViewModel(IReadOnlyListTaskDto items){Tasks items;}/// summary/// 用于过滤下拉框的绑定/// /summary/// returns/returnspublic ListSelectListItem GetTaskStateSelectListItems(){var listnew ListSelectListItem(){new SelectListItem(){Text AllTasks,Value ,Selected SelectedTaskStatenull}};list.AddRange(Enum.GetValues(typeof(TaskState)).CastTaskState().Select(statenew SelectListItem(){Text $TaskState_{state},Value state.ToString(),Selected stateSelectedTaskState}));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);
}
h2L(TaskList)button typebutton classbtn btn-primary data-togglemodal data-target#addCreate Task/buttona classbtn btn-primary data-togglemodal hrefUrl.Action(RemoteCreate) data-target#modal rolebuttonCreate Task使用Remote方式调用Modal进行展现/a!--任务清单按照状态过滤的下拉框--span classpull-rightHtml.DropDownListFor(model model.SelectedTaskState,Model.GetTaskStateSelectListItems(),new{class form-control select2,id TaskStateCombobox})/span
/h2!--任务清单展示--
div classrow idtaskList{ Html.RenderPartial(_List, Model.Tasks); }
/div!--通过初始加载页面的时候提前将创建任务模态框加载进来--
Html.Action(Create)!--编辑任务模态框通过ajax动态填充到此div中--
div idedit/div!--Remote方式弹出创建任务模态框--
div classmodal fade idmodal tabindex-1 roledialog aria-labelledbycreateTask data-backdropstaticdiv classmodal-dialog roledocumentdiv classmodal-content/div/div
/div3Remote方式创建任务讲解
Remote方式就是点击按钮的时候去加载创建任务的PartialView到指定的div中。而我们代码中另一种方式是通过Html.Action(Create)的方式在加载Index的视图的作为子视图同步加载了进来。 感兴趣的同学自行查看源码不再讲解。 a classbtn btn-primary data-togglemodal hrefUrl.Action(RemoteCreate) data-target#modal rolebuttonCreate Task使用Remote方式调用Modal进行展现/a!--Remote方式弹出创建任务模态框--
div classmodal fade idmodal tabindex-1 roledialog aria-labelledbycreateTask data-backdropstaticdiv classmodal-dialog roledocumentdiv classmodal-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);}5js代码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([typehidden]):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.length0) {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 typetext/javascript$(function () {//allow validation framework to parse DOM$.validator.unobtrusive.parse(form);});
/script源码已上传至Github-LearningMpaAbp可自行参考。 作者圣杰 链接https://www.jianshu.com/p/620c20fa511b 来源简书 著作权归作者所有。商业转载请联系作者获得授权非商业转载请注明出处。