Summary on the experience of Bootstrap Metronic development framework "Seven" data import, export and the attachment of view processing _javascript tips

Source: Internet
Author: User
Tags button type

In many system modules, we may all need to do some data exchange processing, that is, the data import or export operations, such batch processing can give the system users a better operating experience, but also improve the user input data efficiency. This article is based on the framework of bootstrap, and then update the module for processing, as well as Office documents or pictures and other accessories to view the processing.

1, the data import operation

General system module inside, there are data import and export operations, so in the interface automatically generated, I tend to give users automatically generate these standard query, import, export and other operating functions, the interface effect is as follows.

Import operations, in the bootstrap framework, I put it as a layer, are unified in the index.cshtml file, so that the entire interface can be handled more closely, the sample code as shown below.

The following code is typically generated automatically, including all the required fields, and we typically tailor the fields to fit our business and actual needs.

<!--import data manipulation layer--> <div id= "import" class= "Modal Fade Bs-modal-lg" "tabindex="-1 "role=" dialog "aria-labelledby="
      Mymodallabel "aria-hidden=" true "> <div class=" Modal-dialog modal-lg "> <div class=" modal-content "> <div class= "Modal-header bg-primary" > <button type= "button" class= "Close" data-dismiss= "modal" Aria-hi Dden= "true" ></button> 

If we want to show the import operation interface, we just need to show this layer, as shown in the following script.

Displays the Import interface
    function Showimport () {
      $ ("#import"). Modal ("show");
    

The file upload processing here, the main use of the Uploadify control to deal with, of course, you can also use the file input upload control I described earlier processing, can be very good to implement these import operations.

In general, the initialization code for the Uploadify control is shown below

$ (function () {//Add-on management of the interface $ (' #file_upload '). Uploadify ({' swf ': '/content/jquerytools/uploadify/uplo            Adify.swf ',//flash file path ' buttontext ': ' Browse ',//Button text ' uploader ': '/fileupload/upload ', Process uploaded page ' queueid ': ' Filequeue ',//queue id ' queuesizelimit ': 1,//queue up to upload file Quantity, default is 999 ' auto ': false,///////////////////////////// True ' removecompleted ': true, remove sequence after completion, default to True ' Filesizelimit ': ' 10MB ',///single file size,            0 is unrestricted, acceptable KB,MB,GB and other units of the string value ' Filetypedesc ': ' Excel files ',//File description ' filetypeexts ': ' *.xls ', Uploaded file suffix filter ' onqueuecomplete ': function (event, data) {//All queues completed event//Business Process code//Prompt user Excel
          Type is normal, if the data is normally loaded}, ' Onuploadstart ': function (file) {initupfile ();//Before uploading a file, reset the GUID, each time different $ ("#file_upload"). UploaDify ("Settings", ' FormData ', {' folder ': ' Data import file ', ' GUID ': $ ("#AttachGUID"). Val ()});  Dynamic Pass Parameters}, ' Onuploaderror ': function (event, Queueid, Fileobj, errorobj) {//alert (errorobj.type
        + ":" + errorobj.info);
    }
      }); });

The key logic is:

Business Process Code

In general, we have been in the server to get the Excel file, so we need to deal with the format of this file, if the format is correct, then we display the data for import users to record the choice, decided to import those records.

The code that handles the format of checking Excel data is shown below.

  Prompts the user if the Excel format is normal, and if the data $.ajax is normally loaded
          ({
            URL: '/user/checkexcelcolumns?guid= ' + GUID,
            type: ' Get '),
            DataType: ' json ',
            success:function (data) {
              if (data). Success) {
                Initgrid ()///re-refresh form data
                showtoast ("file uploaded, Data loaded!") ");
              }
              else {
                showtoast ("uploaded Excel file check does not pass.") Please input data according to the Excel template format in the upper right corner of the page. "," error ");
              }
            }
          );

We are in the background to add a Checkexcelcolumns method, used to check the Excel file field format, only meet the format requirements of the file, only to be captured data and displayed in the interface.

The JS code displayed on the interface, which is mainly extracted from the contents of the Excel file, is bound to the table element.

Query and bind result function Initgrid () {var guid = $ ("#AttachGUID") based on criteria. Val ();
      var url = "/user/getexceldata?guid=" + GUID;
        $.getjson (URL, function (data) {$ ("#gridImport_body"). HTML ("");
          $.each (data.rows, function (I, item) {var tr = "<tr>";
          TR + + "<td><input class= ' checkboxes ' type=\" checkbox\ "name=\" checkbox\ "></td>"; TR + + "<td>" + item.
          Handno + "</td>"; TR + + "<td>" + item.
          Name + "</td>"; TR + + "<td>" + item.  
          FullName + "</td>"; TR + + "<td>" + item.
          Title + "</td>"; TR + + "<td>" + item.
          Mobilephone + "</td>"; TR + + "<td>" + item.
          Officephone + "</td>"; TR + + "<td>" + item.
          Email + "</td>"; TR + + "<td>" + item.
          Gender + "</td>"; TR + + "<td>" + item.
          QQ + "</td>"; TR + + "<td>" + item. Note + "</td> ";
          TR = "</tr>";
        $ ("#gridImport_body"). Append (tr);
      });
    }); }

In order to further obtain the user to import into the specific department, then we can also pop up a dialog box and then select the specific information, and finally submit data to the background to deal with.

The action code is shown below.

Save the imported data
    function Saveimport () {
      //Assigned to Object
      $ ("#Company_ID3"). Select2 ("Val", @Session ["company_id"]). Trigger (' change ');
      $ ("#Dept_ID3"). Select2 ("Val", @Session ["dept_id"]). Trigger (' change ');
      $ ("#selectDept"). Modal ("show");
    

So we confirm the save time, only need to use AJAX to submit the data to the background processing can be, the specific JS code as shown below.

 $.ajax ({
        URL: '/user/saveexceldata ',
        type: ' Post ',
        dataType: ' json ',
        contentType: ' application/ Json;charset=utf-8 ',
        traditional:true,
        success:function (data) {
          if (data). Success) {
            //Save Success 1. Close the pop-up layer, 2. Empty record display 3. Refresh master list
            Showtoast ("Save Success");
            $ ("#import"). Modal ("Hide");
            $ (bodytag). HTML ("");
            Refresh ();
          }
          else {
            Showtoast ("Save failed:" + data.) ErrorMessage, "error");
          }
        },
        data:postdata
      });

2, the data export operation

The export operation of the data is relatively simple, in general, we write the data into a fixed Excel table, and then provide a URL for users to download.

 Export Excel data
    function Showexport () {
      var url = '/user/export ';
      var condition = $ ("#ffSearch"). Serialize ()//Get condition
      executeexport (URL, condition);//execute Export
    }

The specific logical code is shown below

To perform an export operation, output file
function executeexport (URL, condition) {
  $.ajax ({
    type: POST),
    Url:url,
    data: Condition,
    success:function (filePath) {
      var downurl = '/fileupload/downloadfile?file= ' + filePath;
      window.location = Downurl
    }}
  );

3, the Attachment view processing

In most cases, we might want to look at the uploaded files, including Office documents, pictures, and so on that can be previewed, if not, to provide a downloadable local open view.

The previous file describes two ways to preview office, one that uses the preview address of Microsoft Office to preview, one that uses control to generate HTML for previewing, which can be used in combination and configured as needed.

<summary>///the view URL corresponding to the view according to the attachment ID. General rules if it is a picture file, return the view URL address '/fileupload/viewattach ';///if the Office files (Word, PPT, Excel), etc., can be viewed through Microsoft's online view: ' http:// View.officeapps.live.com/op/view.aspx?src= ',///can also generate HTML file views locally.
    If it is another file, you can download the address directly.  </summary>///<param name= "id" > Attachment id</param>///<returns></returns> Public
      ActionResult Getattachviewurl (String id) {String viewurl = ""; Fileuploadinfo info = bllfactory<fileupload>.
      Instance.findbyid (ID); if (info!= null) {string ext = info. Fileextend.trim ('. ').
        ToLower ();
        String FilePath = GetFilePath (info); BOOL Officeinternetview = false;//Whether to use Internet online Preview string hostName = Httputility.urlpathencode ("http://www.iqidi.com/") //Can be configured, if necessary if (ext = = "XLS" | | ext = = "XLSX" | | ext = "DOC" | | ext = "DOCX" | | ext = "PPT" | | ext = = "Pptx ") {if (Officeinternetview) {//returnOne Microsoft online Browsing Office address, need to add Internet domain name or public network IP address Viewurl = string.
          Format ("Http://view.officeapps.live.com/op/view.aspx?src={0}{1}", HostName, FilePath);
            else {#region Dynamic first makefile//check for the presence of the local office file, if it does not exist, Sir, and return to the path for viewing String Webpath = String.
            Format ("/generatefiles/office/{0}.htm", info.id);
            String generatefilepath = Server.MapPath (Webpath); if (! Fileutil.fileisexist (Generatefilepath)) {string templatefile = Bllfactory<fileupload>.
              Instance.getfilepath (info);
              TemplateFile = Path.Combine (System.AppDomain.CurrentDomain.BaseDirectory, Templatefile.replace ("\", "/")); if (ext = = "Doc" | | | ext = = "Docx") {Aspose.Words.Document doc = new Aspose.Words.Document (
                TemplateFile); Doc.
              Save (Generatefilepath, Aspose.Words.SaveFormat.Html); else if (ext = = "XLS" | | ext = "XLSX") {Workbook workbook = new Workbook (templatefile); Workbook.
              Save (Generatefilepath, saveformat.html); else if (ext = = "ppt" | | ext = = "Pptx") {templatefile = Templatefile.replac
                E ("/", "\ \");
                Presentationex pres = new Presentationex (templatefile); Pres.
              Save (Generatefilepath, Aspose.Slides.Export.SaveFormat.Html);
          }} #endregion Viewurl = Webpath;
        } else {viewurl = FilePath;
    } return Content (Viewurl);  }

Through this background processing code, we can correctly know the Office preview, the use of which URL.

So in front of the page, we just need to judge the specific type of file, and then show it.

 if (type = = "image") {
      var imgcontent = '  ';
      $ ("#divViewFile"). HTML (imgcontent);
      $ ("#file"). Modal ("show");
    else {
      $.ajax ({
        type: ' Get ',
        Url:viewurl,
        //async:false,//sync
        //datatype: ' JSON ',
        success : function (JSON) {
          $ ("#divViewFile"). HTML (JSON);
          $ ("#file"). Modal ("show");
        },
        error:function (XHR, status, error) {
          ShowError ("Operation failed" + Xhr.responsetext); Xhr.responsetext
        }
      }); 
    

where the Code

$ ("#file"). Modal ("show");

Is that we call the Global dialog box to show the specific content, and the effect is as follows.

The Word document preview effect looks like this:

Or when we look at the picture file, we can get the interface effect as follows:

The above is a small part of the introduction of bootstrap Metronic development framework based on the experience of "seven" data import, export and accessories to view the relevant content, I hope to help you, if you want to learn more information please pay attention to cloud Habitat community website, In this small series thank you very much for the cloud Habitat Community website support!

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.