A Preliminary Study of abc's CURD and easyuicurd Based on EasyUI

Source: Internet
Author: User

A Preliminary Study of abc's CURD and easyuicurd Based on EasyUI

After finishing the daily overtime project, although the project is over, there is still a small problem. It can only be completed in later optimization. This project adopts MVC, Webapi, Entityframework, in the park, we saw an introduction to the relevant ABP, which is also the latest technology set. We joined the 134710707 technology exchange group for the design of the ABP architecture to discuss, learn, and make progress together.

The technical documents of the ABP are all in English, but now you don't have to worry about it. Enthusiastic friends in the group have translated the documents into easy-to-understand languages. For details

ABP Source Code address https://github.com/aspnetboilerplate

This document is based on. net 4.5.1. After downloading the document, I will explain how to use it.

The company's projects are based on Easyui, so the Demo is also based on EasyUI. the return value of ABP cannot meet the datagrid request and display of Easyui, and some changes to the source code of the Abp can be used normally, the specific changes will be listed one by one to help you.

The first letter of the object property returned by the request value of the ABP is lowercase, because the default Json format is CamelCasePropertyNamesContractResolver. You only need to modify the relevant code

Corresponding Class Name: AbpWebApiModule

private static void InitializeFormatters()        {            GlobalConfiguration.Configuration.Formatters.Clear();            var formatter = new JsonMediaTypeFormatter();            formatter.SerializerSettings.ContractResolver = new DefaultContractResolver();            formatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";            GlobalConfiguration.Configuration.Formatters.Add(formatter);            GlobalConfiguration.Configuration.Formatters.Add(new PlainTextFormatter());        }

Easyui's Datagrid request uses a URL to pass parameters. Currently, this processing method is not supported by abc. therefore, you can only write the method in the Controller and cannot call the automatically generated WebAPi, one more step is required. The following is the constructed paging class.

public EasyUIPager GetPager(HttpRequestBase currentRequest)        {            EasyUIPager pager = new EasyUIPager();            if (currentRequest.Form["page"] != null)            {                pager.CurrentPage = int.Parse(currentRequest.Form["page"]);            }            if (currentRequest.Form["rows"] != null)            {                pager.PageSize = int.Parse(currentRequest.Form["rows"]);            }            pager.SortCloumnName = currentRequest.Form["sort"];            pager.SortOrder = currentRequest.Form["order"];            pager.Filter = currentRequest.Form["filter"];            return pager;        }

JS request Call Code

Function GridInit () {// VE. loodToolbar (); // load permission datagrid =$ ("# datagrid "). datagrid ({url: VE. appPath + '/User/get', title: 'user information', rownumbers: true, pagination: true, iconCls: VE. datagridIconCls, height: VE. gridHeight, pageSize: VE. pageSize, pageList: VE. pageList, ctrlSelect: true, fitColumns: true, nowrap: false, border: true, idField: 'id', sortName: 'id', sortOrder: 'desc', columns: [[{field: 'ck ', checkbox: true}, {field: 'id', title: 'id', width: 80, sortable: true, hidden: true }, {field: 'username', title: 'username', width: 100, sortable: true}, {field: 'surname', title: 'surname', width: 60, sortable: true}, {field: 'name', title: 'name', sortable: true}, {field: 'emailaddress', title: 'mailbox ', sortable: true}, {field: 'creationtime', title: 'creation time', width: 140, sortable: true}, {field: 'creatorusername', title: 'creator ', width: 100, sortable: true}, {field: 'lastmodifierusername', title: 'Last updater', width: 100, sortable: true}, {field: 'lastmodificationtime ', title: 'Last update time', width: 140, sortable: true, formatter: VE. formatterDateTime}, {field: 'isactive', title: 'status', width: 45, sortable: true, formatter: VE. formatterActive}], toolbar: [{iconCls: 'icon-add', text: 'add', handler: function () {id = 0; Save ()}}, '-', {iconCls: 'icon-edit', text: 'edit', handler: function () {id = VE. edit ("datagrid", VE. gridType_DataGrid) if (id> 0) {Save () ;}}, '-', {iconCls: 'icon-busy', text: 'delete', handler: function () {Delete () ;}}, '-', {iconCls: 'icon-unlock', text: 'enabled', handler: function () {Active (true) }}, '-', {iconCls: 'icon-lock', text: 'deactivated ', handler: function () {Active (false) }}]});}View Code

MVC Controller code

# Region Get list public JsonResult Get () {var provider = new EasyUIProvider (); var pager = provider. GetPager (Request); var filter = new GetUserInput (); if (! String. isNullOrEmpty (pager. filter) {filter = provider. deserializeObject <GetUserInput> (pager. filter);} filter. pageSize = pager. pageSize; filter. currentPage = pager. currentPage-1; filter. sortOrder = pager. sortOrder; filter. sortCloumnName = pager. sortCloumnName; var grid = _ userApplicationService. getUser (filter); return Json (grid) ;}# endregionView Code

As follows:

 

With regard to the creator and the last updated person, the process of the ABP is better. You only need to map it and do not need to write redundant subqueries. The source code has not been viewed for the specific principle, I will explain it later.

For batch operations, the page is usually 20 ~ 50 pieces of data, simple batch deletion can basically meet the requirements. If you need to operate a large amount of data, it is recommended to use the stored procedure. Modification and addition are not described. For specific implementation, refer to the source code.

 public async Task Delete(BatchDeleteRequestInput input)        {            for (int i = 0; i < input.Id.Split(',').Length; i++)            {                await _userRepository.DeleteAsync(Convert.ToInt64(input.Id.Split(',')[i]));            }            await _unitOfWorkManager.Current.SaveChangesAsync();        }

The processing of UserFriendlyException is modified. A prompt box is displayed for different exceptions.

Public UserFriendlyException (string message, UserFriendlyExceptionCode): base (message) {if (code = UserFriendlyExceptionCode. info) {Code = 1;} else if (code = UserFriendlyExceptionCode. warn) {Code = 2 ;}else {Code = 0 ;}}View Code

EasyUI code

$. Ajax ({url: VE. appPath + url, type: 'post', contentType: 'application/json', data: json. stringify ({Id: VE. ids. join (','), IsActive: active}), ype: 'json', success: function (r) {if (r. success) {VE. messageShow ("operation successful"); VE. gridJudge (gridId, isLoad, gridType);} else {if (r. error. code = 0) {$. messager. alert ('hprompt ', r. error. message, "error");} else if (r. error. code = 1) {$. messager. alert ('hprompt ', r. error. message, "info");} else if (r. error. code = 2) {$. messager. alert ('hprompt ', r. error. message, "warn");} else {$. messager. alert ('hprompt ', r. error. message, "error ");}}}});View Code

The project structure is as follows:

We all like the source code. F5 runs directly, so we wrote a demo for your reference.

Source code download

 

Set V. Market. Web as the startup project

Modify the connection string of web. config

<Add name = "Default" connectionString ="Data source =.; initial catalog = Market; persist security info = True; user id = sa; password = Password !; MultipleActiveResultSets = True; App = EntityFramework"ProviderName =" System. Data. SqlClient "/>

Some Garden friends have not studied EntityFramework, but do not know how to generate a database. The following describes how to generate a database.

Generate database update-database using commands (data can be written to the database only after the database is run twice)

Modify the TenantId of the generated data abpuser table to 1.

Because you forgot to modify the logon username when uploading the code, you must change the logon username of HomeController to Admin.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.