【jQuery】【ajax】【C#】【Web API】【Web Service】【MVC5】前端頁面用ajax call web api,data傳dictionary參數

前端頁面用ajax call web api,data傳dictionary參數

Web API:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPI
{
    [RoutePrefix("api/Doc")]
    public class DocController : ApiController
    {
        /// <summary>
        /// 指定的word檔案套用模版,代入指定內容,並下載
        /// </summary>
        /// <param name="wordProcessData">自訂的Class,裝載要處理Word檔用的參數</param>
        /// <returns>處理結果</returns>
        [HttpPost, Route("DownloadDoc")]
        public HttpResponseMessage DownloadDoc(WordProcessData wordProcessData)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                //表頭模版word檔的路徑
                string sHeaderDocUNCPath = wordProcessData.HeaderDocUNCPath;
                //要套用表頭的word檔路徑
                string sContentDocUNCPath = wordProcessData.ContentDocUNCPath;
                //要代換表頭模版欄位資訊的內容
                Dictionary<object, object> textToReplace = wordProcessData.HeaderTextPairToReplace;

                //自訂的Class,處理word換表頭。會開啟處理好的word檔,等待User手動檢視存檔
                new WordProcessInterop().Process(sHeaderDocUNCPath, sContentDocUNCPath, textToReplace);
            }
            catch (Exception err)
            {
                response.StatusCode = HttpStatusCode.ExpectationFailed;
                response.Content = new StringContent(err.Message);
            }

            return response;
        }
    }
}

HTML:(留意檔案路徑要多加"\"做escape)(這裡面有些參數用不到)

<button type="button" class="btn btn-secondary btn-sm" id="ImageButton1" onclick="DownloadProcessedDoc('\\\\MySever\\MyFolder1\\MyFolder2\\MyContent.docx','9','John','Amy','MyChineseTitle','MyChineseTitle','MyEnglishTitle','MyEnglishTitle','MyFormNumber','MyFolder1\\MyFolder2\\','\\\\MySever\\','MyHeader.docx');" >

JavaScript,用jQuery ajax call Web API:

<script type="text/javascript">
    function DownloadProcessedDoc(sContentDocPath,str1,str2,str3,str4,str5,str6,str7,str8,sTemplateFolder,sTemplateFolderDocServer, sHeaderTemplateFilename) {
		var param = {
            'HeaderDocUNCPath': $.trim(sTemplateFolderDocServer) + $.trim(sTemplateFolder) + $.trim(sHeaderTemplateFilename),

            'ContentDocUNCPath': sContentDocPath,

            'HeaderTextPairToReplace[0].Key': '-FormNo-', 
            'HeaderTextPairToReplace[0].Value': str8,

            'HeaderTextPairToReplace[1].Key': '-Author-', 
            'HeaderTextPairToReplace[1].Value': str3,

            'HeaderTextPairToReplace[2].Key': '-Version-', 
            'HeaderTextPairToReplace[2].Value': (parseInt(str1)+1).toString(),

            'HeaderTextPairToReplace[3].Key': '-DocChineseName-', 
            'HeaderTextPairToReplace[3].Value': str5,

            'HeaderTextPairToReplace[4].Key': '-DocEnglishName-', 
            'HeaderTextPairToReplace[4].Value': str7,
        };

        $.ajax({
            type: 'POST',
            url: 'http://www.abc.com/MyWebAPI/api/Doc/DownloadDoc',
            cache: false,
            async: false,
            dataType: 'json',
            data: param,
            success: function (response) {
                if (response.success) {
                    alert('成功');
                }
                else {
                    alert('[System Error]' + response.message);
                }
            },
            error: function () {
                alert('Fail' + 'DownloadProcessedDoc());
            }
        });
    };
</script>