Google Code Prettify

[MVC] @Html.Raw() 釋意與用法

@Html.Raw()
註釋:將帶有的HTML標籤的字符串,轉換成的HTML標籤輸出


用法:

@{
   var message =“<script> alert("測試輸出")</script>”
}



例:

@{
   var message =“<script> alert("測試輸出")</script>”
}

<html>
<head>
    <title></title>
</head>
<body>
    @Html.Raw(@message)
</body>
</html>





[MVC]多檔上傳

View


修改 \Views\Shared\_Layout.cshtml ,增加下列連接資料:

@Html.ActionLink("檔案上傳", "Index", "FileUpload", new { area = "" }, null)



增加 \Views\FileUpload\Index.cshtml

@model WebServiceTest.Models.UploadFileInfo

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<div>@ViewBag.Message</div>
@using(Html.BeginForm("Index", "FileUpload", 
    new { ReturnUrl = ViewBag.ReturnUrl }, 
    FormMethod.Post, new { @class = "form-inline", role = "form", enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <input type="file" name="FileName" id="FileName" multiple="multiple" />
    <img id="image1" src="" />
    <br /><br />
    <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
}

@section  scripts{
    <script>
        $("#FileName").change(function () {
            InputLoadImageToBindImageElement(this, $('#image1'));
        });
        function InputLoadImageToBindImageElement(inputEl, imgEl) {
            if (inputEl.files && inputEl.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(imgEl).attr('src', e.target.result);
                }
                reader.readAsDataURL(inputEl.files[0]);
            }
        }
    </script>
}




Controller


增加 \ControllersForUser\FileUploadController.cs

using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using WebServiceTest.Models;

namespace WebServiceTest.ControllersForUser {
    public class FileUploadController : Controller {
        // GET: FileUpload
        public ActionResult Index() {
            UploadFileInfo uploadFileInfo = new UploadFileInfo();
            return View(uploadFileInfo);
        }
        [HttpPost]
        public ActionResult Index(UploadFileInfo uploadFileInfo) {
            foreach(string upload in Request.Files) {
                if(!(Request.Files[upload] != null && Request.Files[upload].ContentLength > 0))
                    continue;
                int memUsage_baseline_id = 0;
                int timingComp_baseline_id = 0;
                if(upload == "FileUploadMemoryUsage" || upload == "FileUploadResultsComparison")
                    if(upload == "FileUploadMemoryUsage")
                        if(Request.Params["memUsage_project"] == null || Request.Params["memUsage_project"] == "")
                            ModelState.AddModelError("Project", "Please Select Project for Memory Usage");
                        else
                            memUsage_baseline_id = int.Parse(Request.Params["memUsage_project"]);
                    else
                        if(Request.Params["resultsComp_project"] == null || Request.Params["resultsComp_project"] == "")
                        ModelState.AddModelError("Project", "Please Select Project for Timing Comparison");
                    else
                        timingComp_baseline_id = int.Parse(Request.Params["resultsComp_project"]);
                HttpPostedFileBase file = Request.Files[upload];
                if(ModelState.IsValid)
                    if(file == null)
                        ModelState.AddModelError("File", "Please Upload Your file");
                    else if(file.ContentLength > 0) {
                        int MaxContentLength = 1024 * 1024 * 3; //3 MB
                        string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
                        if(!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                            ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                        else if(file.ContentLength > MaxContentLength)
                            ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                        else {
                            if(!Directory.Exists(Server.MapPath("~/Upload")))
                                Directory.CreateDirectory(Server.MapPath("~/Upload"));
                            var fileName = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                            file.SaveAs(path);
                            ModelState.Clear();
                            //ViewBag.Message = "File uploaded successfully";
                            TempData["message"] = "File uploaded successfully";
                        }
                    }
            }
            return View();
        }
    }
}

[MVC] Razor @RenderSection

RenderSection 主要的用途是在主版面 _layout.cshtm 中定義一些區塊。



像是以下這段

    <div id="body">
        <div class="container">
            @RenderSection("featured", required: false)
            <section class="content-wrapper clear-fix">
                @RenderBody()
            </section>
        </div>
    </div>
    <footer>
        @Html.Partial("Footer")
    </footer>
    @RenderSection("scripts", required: false)

微軟預設主版面的程式碼



@RenderBody() 是會產生其他view的畫面

@RenderSection("featured", required: false)  這個就是主版面預留的section

此方法的第二個參數  就是設定這個section是不是每個頁面都一定要實作

設定false 就是不用每個頁面都實作

true的時候 就每個頁面一定都要有這個區塊

不然會出現exception

要在每個頁面設定值的方法如下

@section featured {
    <div class="jumbotron">
        <h1>@ViewBag.CategoryName.</h1>
        <p>@ViewBag.Message</p>
    </div>
}

這樣就會在主版頁面featured區塊顯示這段HTML

同理 要使用@RenderSection("scripts", required: false)這塊

就這樣設定

@section scripts {
   <script>
         $(document).ready(function () {
            initForm();
        });
   </script>
}


此時如果對版面比較要求的人就會延伸出一個問題,我如果有頁面不想設定此區塊,能不能給他預設值,因為我懶得每一頁都設定預設值

此時可以使用IsSectionDefined來判斷頁面有沒有設定section

    @if (IsSectionDefined("featured"))
    {
        @RenderSection("featured", required: false)
    }
    else
    {
        <p>Section not define.</p>
    }

[Javascript][MVC] Input file 選取檔案後預覽圖片

選取一個圖片檔案後,直接進行預覽


<script>
function InputLoadImageToBindImageElement(inputEl, imgEl) {
 
    if (inputEl.files && inputEl.files[0]) {
        var reader = new FileReader();
 
        reader.onload = function (e) {
            $(imgEl).attr('src', e.target.result);
        }
 
        reader.readAsDataURL(inputEl.files[0]);
    }
}
</script>




HTML

<img src="" id="image1" />
<input type="file" name="name" id="iptImage1" value="" />





呼叫


<script>
$("#iptImage1").change(function () {
          InputLoadImageToBindImageElement(this, $('#image1'));
});
</script>



注意:
本文中的 Script 都必須放在 Form 的後面,或者乾脆就放在頁面的最下方,以免找不到 Input 而報錯。






MVC 中可用下面的方法叫用


@model WebServiceTest.Models.UploadFileInfo

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<div>@ViewBag.Message</div>
@using(Html.BeginForm("Index", "FileUpload", 
       new { ReturnUrl = ViewBag.ReturnUrl }, 
       FormMethod.Post, 
       new { @class = "form-inline", role = "form", enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <input id="FileName" multiple="multiple" name="FileName" type="file" />
    <img id="image1" src="" />
    <input id="btnSubmit" name="btnSubmit" type="submit" value="Submit" />
}

@section  scripts{
    <script>
        $("#FileName").change(function () {
            InputLoadImageToBindImageElement(this, $('#image1'));
        });
        function InputLoadImageToBindImageElement(inputEl, imgEl) {
            if (inputEl.files && inputEl.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(imgEl).attr('src', e.target.result);
                }
                reader.readAsDataURL(inputEl.files[0]);
            }
        }
    </script>
}







Unit test sample code

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Http;
using System.Web.Http.Results;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using WebServiceTest.Controllers;
using WebServiceTest.Models;

namespace WebServiceTest.Tests.Controllers {
    [TestClass()]
    public class ProductsControllerTest {
        public CancellationToken _cancellationToken { get; set; }
        public ProductsControllerTest() {
            _cancellationToken = new CancellationToken();
        }
        // 取得所有產品項目明細
        [TestMethod()]
        public void GetAllProducts() {
            ProductsController controller = new ProductsController();
            IEnumerable<Product> result = controller.GetAllProducts();
            Assert.IsNotNull(result);             // 檢查有沒有資料
            Assert.AreEqual(3, result.Count());   // 檢查資料的筆數
            Assert.AreEqual("Tomato Soup", result.ElementAt(0).Name);    // 資料內容比對
            Assert.AreEqual("Yo-yo", result.ElementAt(1).Name);          // 資料內容比對
            Assert.AreEqual("Hammer", result.ElementAt(2).Name);          // 資料內容比對
        }
        // 取得各產品的資料內容
        [TestMethod()]
        public void GetProduct() {
            ProductsController controller = new ProductsController();
            // 取得傳回的 IHttpActionResult, 轉成資料物件, 以取得內容
            IHttpActionResult actionResult1 = controller.GetProduct(1);
            var contentResult1 = (OkNegotiatedContentResult<Product>)actionResult1;
            IHttpActionResult actionResult2 = controller.GetProduct(2);
            var contentResult2 = (OkNegotiatedContentResult<Product>)actionResult2;
            IHttpActionResult actionResult3 = controller.GetProduct(3);
            var contentResult3 = (OkNegotiatedContentResult<Product>)actionResult3;           
            Assert.AreEqual("Tomato Soup", contentResult1.Content.Name);    // 資料內容比對
            Assert.AreEqual("Yo-yo", contentResult2.Content.Name);          // 資料內容比對
            Assert.AreEqual("Hammer", contentResult3.Content.Name);         // 資料內容比對
        }
    }
}

REST Web Service Response Codes

- Result of request operation
- 1xx series(100-199) - informational
- 2xx series - Success
- 3xx series - Redirection
- 4xx series - Client Error
- 5xx series - Server Error


Some commom codes:
200 OK
300 Multiple Choices
301 Moved Permanently
302 Found
304 Not Modified
307 Temporary Redirection
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
410 Gone
500 Internal Server Error
501 Not Implemented
503 Service Unavailable
550 Permission denied

[WebAPI]將 JSON 字串 POST 到 Web API

要將 JSON 編碼內容 POST 到 Web API, 首先要先準備一支方法程式 (method),用 JSON.NET 將資料轉換成 JSON 格式的字串資料,再利用 HttpClient 將它送到 Web API (遠端伺服器端) ,這一支方法程式的範例如下: ( JsonPostAsync method)


private static async Task<apiresult> JsonPostAsync(APIData apiData)
{
    APIResult fooAPIResult;
    using (HttpClientHandler handler = new HttpClientHandler())
    {
        using (HttpClient client = new HttpClient(handler))
        {
            try
            {
                #region 呼叫遠端 Web API
                string FooUrl = $"http://localhost:8089/api/Values"; 
                HttpResponseMessage response = null;

                #region  設定相關網址內容
                var fooFullUrl = $"{FooUrl}";

                // Accept 用於宣告客戶端要求服務端回應的文件型態 (底下兩種方法皆可任選其一來使用)
                //client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Content-Type 用於宣告遞送給對方的文件型態
                //client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

                var fooJSON = JsonConvert.SerializeObject(apiData);
                // https://msdn.microsoft.com/zh-tw/library/system.net.http.stringcontent(v=vs.110).aspx
                using (var fooContent = new StringContent(fooJSON, Encoding.UTF8, "application/json"))
                {
                    response = await client.PostAsync(fooFullUrl, fooContent);
                }
                #endregion
                #endregion

                #region 處理呼叫完成 Web API 之後的回報結果
                if (response != null)
                {
                    if (response.IsSuccessStatusCode == true)
                    {
                        // 取得呼叫完成 API 後的回報內容
                        String strResult = await response.Content.ReadAsStringAsync();
                        fooAPIResult = JsonConvert.DeserializeObject<apiresult>(strResult, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore });
                    }
                    else
                    {
                        fooAPIResult = new APIResult
                        {
                            Success = false,
                            Message = string.Format("Error Code:{0}, Error Message:{1}", response.StatusCode, response.RequestMessage),
                            Payload = null,
                        };
                    }
                }
                else
                {
                    fooAPIResult = new APIResult
                    {
                        Success = false,
                        Message = "應用程式呼叫 API 發生異常",
                        Payload = null,
                    };
                }
                #endregion
            }
            catch (Exception ex)
            {
                fooAPIResult = new APIResult
                {
                    Success = false,
                    Message = ex.Message,
                    Payload = ex,
                };
            }
        }
    }

    return fooAPIResult;
}


接下來,我們須在控制器 (Controller) 中加上一個 Post 的方法 (method),

[HttpPost]
public APIResult Post([FromBody]APIData value)
{
    APIResult foo;

    if (value.Id == 777)
    {
        foo = new APIResult()
        {
            Success = true,
            Message = "透過 post 方法,接收到 Id=777 資料",
            Payload = value
        };
    }
    else
    {
        foo = new APIResult()
        {
            Success = false,
            Message = "無法發現到指定的 ID",
            Payload = null
        };
    }
    return foo;
}


在這個 Post 方法中,我們帶入一個 APIData 型別的物件,當物件中 Id 這個屬性值為 777 的時候,在 Web API 的動作將會回覆這次的呼叫是成功的且傳回資料型別為 APIData 的 value 物件,否則,會回覆此次呼叫失敗(無法發現到指定的 ID),並傳回 null。


在 Post 的方法實作完成後,接著我們要準備程式的進入點方法(Main method)。


static void Main(string[] args)
{
    var fooAPIData = new APIData()
    {
        Id = 777,
        Name = "VulcanSource",
    };
    var foo = JsonPostAsync(fooAPIData).Result;
    Console.WriteLine($"使用 JSON 格式與使用 Post 方法呼叫 Web API 的結果");
    Console.WriteLine($"結果狀態 : {foo.Success}");
    Console.WriteLine($"結果訊息 : {foo.Message}");
    Console.WriteLine($"Payload : {foo.Payload}");
    Console.WriteLine($"");

    Console.WriteLine($"Press any key to Exist...{Environment.NewLine}");
    Console.ReadKey();

    fooAPIData = new APIData()
    {
        Id = 123,
        Name = "VulcanSource",
    };
    foo = JsonPostAsync(fooAPIData).Result;
    Console.WriteLine($"使用 JSON 格式與使用 Post 方法呼叫 Web API 的結果");
    Console.WriteLine($"結果狀態 : {foo.Success}");
    Console.WriteLine($"結果訊息 : {foo.Message}");
    Console.WriteLine($"Payload : {foo.Payload}");
    Console.WriteLine($"");

    Console.WriteLine($"Press any key to Exist...{Environment.NewLine}");
    Console.ReadKey();
}


方法中我們分為兩個部分,先是傳送  Id 這個屬性值為 777 的資料到 Web API ,接著再傳送  Id 這個屬性值為 123 的資料到 Web API ,看看這兩個部分執行後得到的結果是不是如預期。


在此,執行結果我們就不再演示,希望此文章能對你有幫助。