Web Development Framework experience based on MVC4 + EasyUI (14) -- automatically generate icon style files and Icon selection operations, mvc4easyui

Source: Internet
Author: User

Web Development Framework experience based on MVC4 + EasyUI (14) -- automatically generate icon style files and Icon selection operations, mvc4easyui

In many Web systems, some icons may be selected to facilitate the configuration of buttons, menus, and other interface elements, but the Web system interface looks more beautiful and harmonious. However, in the system, the built-in icon styles are relatively limited, and hard encoding is written into the style sheet, which makes it inconvenient for us to expand and use. For this reason, I think if I can create an independent module, automatically generate an icon CSS style File Based on the icon, and store the corresponding records in the database for our convenience, this makes it easy to use. With this data, you only need to make a general icon selection interface and reuse it in many places. Based on this idea, this article develops an icon management module and an icon selection interface. This article mainly describes the development process and the final effect presentation.

1. Manage icon style generation

To generate a corresponding icon Style File Based on the list of read Icon files, we can use the NVelocity component to generate CSS style files based on templates. For more information about how to use NVelocity, refer to my many articles about it. This component is very powerful. My own code generation tool also compiled many templates based on it for code generation, for details, refer to the article "several ways to generate content using NVelocity.

1.1 icon style file preparation

With these preparations, we can define a template file to generate a style file. Let's first look at the final Style File effect.

.icon-table{    background:url('table.png') no-repeat center center;}.icon-telephone{    background:url('telephone.png') no-repeat center center;}.icon-user{    background:url('user.png') no-repeat center center;}.icon-view{    background:url('view.png') no-repeat center center;}.icon-word{    background:url('word.png') no-repeat center center;} 

Based on the above organizational results, we can define a template as follows.

#foreach($item in ${FileNameList}).${item.Text}{    background:url('${item.Value}') no-repeat center center;}#end ##endforeach

The FileNameList variable is a set object based on names and values. We can traverse it to generate it.

1.2 create an icon Style

With templates, we also need to organize the corresponding file directories. Generally, the standard size charts 16, 24, and 32 can be used for Web icons to meet the needs of different scenarios.

Therefore, we create several different directories and add the corresponding template files and Icon files.

To generate an icon Style File, follow these steps:

Obtain the icon file of the corresponding directory, convert it to the actual object format set, generate the icon style file, and store the chart style to the database for convenient query.

These operations are performed on the controller of icon management.IconControllerThe method is added, and some code is as follows.

/// <Summary> /// generate the icon file /// </summary> /// <param name = "iconSize"> chart size, optional 16, 32, etc. </param> // <returns> </returns> public ActionResult GenerateIconCSS (int iconSize = 16) {CommonResult result = new CommonResult (); string realPath = Server. mapPath ("~ /Content/icons-customed/"+ iconSize); if (Directory. exists (realPath) {List <CListItem> list = GetImageToList (realPath, iconSize); try {// use the relative path to construct and process string template = string. format ("Content/icons-customed/{0}/icon.css. vm ", iconSize); NVelocityHelper helper = new NVelocityHelper (template); helper. addKeyValue ("FileNameList", list); helper. fileNameOfOutput = "icon"; helper. fileExtension = ". css "; Helper. DirectoryOfOutput = realPath; // specify the actual path string outputFilePath = helper. ExecuteFile (); if (! String. isNullOrEmpty (outputFilePath) {result. success = true; // write to the database bool write = BLLFactory <Icon>. instance. batchAddIcon (list, iconSize) ;}} catch (Exception ex) {LogTextHelper. error (ex); result. errorMessage = ex. message ;}} else {result. errorMessage = "Image File not found";} return ToJsonContent (result );}

The above method completes the generation and storage of the icon style database. This generation operation is mainly based on Template generation, which is very convenient.

When building a set of name values, note that the icon style name cannot contain special characters, such, therefore, you can use the following regular expression replacement method to remove it.

String displayText = Path. getFileNameWithoutExtension (file); // remove the () and [] symbols such as displayText = CRegex for the file name. replace (displayText, @ "[) \];, \ t \ r] | [\ n]", "", 0); displayText = CRegex. replace (displayText, @ "[(\ []", "-", 0 );

Finally, we can build an independent page to generate and save the icon style, as shown in the following figure.

The interface operation code is as follows.

// Click the BindEvent () {$ ("# btnGenerateCSS") event of the BIND button "). click (function () {$. messager. confirm ("Operation confirmation", "Are you sure you want to regenerate the icon record? ", Function (action) {if (action) {// chart size var iconSize = $ (" # IconSize "). combobox ('getvalue'); // alert (iconSize); var postData = ""; $. ajax ({type: 'post', url: '/Icon/GenerateIconCSS? IconSize = '+ iconSize, ype: 'json', data: postData, success: function (data) {if (data. success) {showTips ("operation successful"); location. reload ();} else {showError ("operation failed:" + data. errorMessage, 3000 );}}});}});});}

2. pagination of icons

To effectively view the icon list generated in the database, we need a reasonable interface to display the icon information. The traditional method of using datagrid is relatively rigid and not very convenient. Therefore, we need to customize pagination for presentation. Based on the Principle of reusing some excellent components, I focused on using some ready-made component modules, MVC paging, and considering using Yang Tao's MVC paging controls (http://www.webdiyer.com/mvcpager/), this feature looks good.

The chart display method. I hope to use the easyui example to show the effect of a group of charts.

2.1 graphic display interface effect

Then, the system processes them by PAGE and selects some good paging style representations.

The chart style display effect is as follows.

The effect of the small icon is as follows.

The big icon effect is as follows.

 

2.2 pagination of icons

Yang Tao's paging control provides many paging binding methods, but it mainly uses MVC-based model data processing. In my Web framework, it mainly uses JS to bind data. There are some differences, however, since we all use MVC applications, integration is still okay.

To show the above results, we need to create a form query content, the Code is as follows.

<Fieldset> <legend> function operation </legend> @ using (Html. beginForm ("select", "Icon", new RouteValueDictionary {"id", "" }}, forw.hod. get) {<span> size: </span> <select class = "easyui-combobox" id = "IconSize" name = "IconSize" style = "width: 100px "> <option value =" 16 "> 16 × 16 </option> <option value =" 24 "> 24 × 24 </option> <option value =" 32"> 32 × 32 </option> </select> <input type = "submit" value = "Search (S) "accesskey =" S "/>}</fieldset>

The presentation of data content mainly uses the easyUI style to create some linkbutton Code. The Code is as follows. Here, we also use the model, which is of the PagedList <WHC. MVCWebMis. Entity. IconInfo> type.

That is to say, at the end of the View Interface, there is a model bound.

        <div id="contents">            @using Webdiyer.WebControls.Mvc;            @model  PagedList<WHC.MVCWebMis.Entity.IconInfo>            @foreach (var item in Model)            {                <a href="javascript:void(0)" class="easyui-linkbutton" onclick="SelectItem(this, '@item.IconCls')" id="@item.ID" data-options="plain:true,iconCls:'@item.IconCls',size:'large',toggle:true"> </a>            }        </div>

The following figure shows the Controller Method for icon background processing.

/// <Summary> /// obtain the object set based on PagedList according to the conditions, and return to the paging view using /// </summary> /// <param name = "id"> page number </param> /// <param name = "iconsize"> Icon size </param> /// <returns> </returns> private PagedList <IconInfo> GetPageList (int? Id, int? Iconsize = 16) {int size = iconsize ?? 16; int pageIndex = id ?? 1; int pageSize = 200; PagerInfo pagerInfo = new PagerInfo (); pagerInfo. currenetPageIndex = pageIndex; pagerInfo. pageSize = pageSize; string where = string. format ("iconsize = {0}", size); List <IconInfo> list = BLLFactory <Icon>. instance. findWithPager (where, pagerInfo); PagedList <IconInfo> pageList = new PagedList <IconInfo> (list, pageIndex, pageSize, pagerInfo. recordCount); return pageLis T;} // <summary> // obtain the paging data set based on the conditions, and bind it to the view. /// </summary> /// <param name = "id"> page number </param> /// <param name = "iconsize"> icon size </param> /// <returns> </returns> public ActionResult Select (int? Id = 1, int? Iconsize = 16) {PagedList <IconInfo> pageList = GetPageList (id, iconsize); return View ("select", pageList );}

The last part is the page display, that is, the page number and other information of each page are displayed at the bottom.

The Code is as follows.

<Div> <div style = "float: left; width: 50%"> @ Model. totalPageCount page @ Model. totalItemCount record, currently @ Model. currentPageIndex page </div> @ Html. pager (Model, new PagerOptions {PageIndexParameterName = "id"}, new {style = "float: right", id = "badoopager"}) </div>

During paging, the condition disappears after the page is updated. This is because the value of the binding condition is not very good on the page. After loading the page, assign the parameter values in the URL to the control.

        $(function () {            var iconSize = '@Request.QueryString["iconSize"]';            if(iconSize != undefined && iconSize != "")            {                $("#IconSize").combobox('setValue', iconSize);            }        });

In this way, the condition of the chart size can always be the correct content, and can still be maintained after the form is submitted.

3. Icon Selection

Since the icon file is generated and the icon display interface is built, we need to provide an interface to select the icon in some places where the icon needs to be configured.

In addition to EasyUI, you can use the extension dialog box to bring up an external page selection Icon menu.

Function SelectIcon (id, value) {$. showWindow ({title: 'select icons ', useiframe: true, width: 960, height: 640, content: 'url:/Icon/select', data: {id: $ (id), value: $ (value)}, buttons: [{text: 'OK', iconCls: 'icon-OK ', handler: 'dook' // This token is in _content3.html}, {text: 'cancel', iconCls: 'icon-cancel', handler: function (win) {win. close () ;}}], onLoad: function (win, content) {// called when window is opened, initialize form content if (content) {content. doInit (win) ;}}}) ;}// BindSelectIconEvent () {$ ("# tdIcon") of the event function bound to the selection button "). click (function () {SelectIcon ("# imgIcon", "# WebIcon")}); $ ("# tdIcon1 "). click (function () {SelectIcon ("# imgIcon1", "# WebIcon1 ")});}

After selecting each icon, we will return to the main interface and set the chart style on the main interface to show the selected icon effect.

 

A series of articles based on the MVC4 + EasyUI Web development framework:

Web development framework formation based on MVC4 + EasyUI-Overview

A journey towards the formation of Web development framework based on MVC4 + EasyUI -- Design of MVC Controller

A journey towards the formation of Web development framework based on MVC4 + EasyUI-Use of interface controls

Creation of Web development framework based on MVC4 + EasyUI -- Use of the attachment Upload Component uploadify

A journey towards the formation of Web development framework based on MVC4 + EasyUI-Overview of the overall framework Interface

A journey towards the formation of Web development framework based on MVC4 + EasyUI-operations of the basic class controller CRUD

A journey of Web development framework based on MVC4 + EasyUI -- permission Control

Summary of Web Development Framework experience based on MVC4 + EasyUI (1)-display SELECTION records using the jQuery Tags Input plug-in

Summary of Web Development Framework experience based on MVC4 + EasyUI (2)-build a Web interface using the EasyUI tree control

Summary of Web Development Framework experience based on MVC4 + EasyUI (3)-build menu data using Json object classes

Summary of Web Development Framework experience based on MVC4 + EasyUI (4) -- use the chart control Highcharts

Summary of Web Development Framework experience based on MVC4 + EasyUI (5) -- use the HTML editing controls CKEditor and CKFinder

Summary of Web Development Framework experience based on MVC4 + EasyUI (6) -- process the application drop-down list on the page

Summary of Web Development Framework experience based on MVC4 + EasyUI (7)-linkage between provinces, cities, and Administrative Districts

Summary of Web Development Framework experience based on MVC4 + EasyUI (8) -- preview Office documents

Summary of Web Development Framework experience based on MVC4 + EasyUI (9) -- Implement escape operations for foreign key fields in the Datagrid

Summary of Web Development Framework experience based on MVC4 + EasyUI (10) -- data import and export on the Web interface

Summary of Web Development Framework experience based on MVC4 + EasyUI (11) -- use Bundles to simplify Page code

Summary of Web Development Framework experience based on MVC4 + EasyUI (12) -- several methods of using Jquery to process data interaction

Summary of Web Development Framework experience based on MVC4 + EasyUI (13) -- DataGrid Control to automatically adapt to broadband height

Web Development Framework experience based on MVC4 + EasyUI (14) -- automatically generate icon style files and Icon Selection

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.