2015年10月27日 星期二

【ASP.NET MVC】JSON from client to server



範例會在 Client 端動態產生 table row 暫存資料,並在 submit 前將表格資料轉為 JSON 格式字串寫入 hiddenfield 以轉給後端,後端會將讀入的 JSON 字串反序列化為 List 後進行簡單的過濾,並再次回給前端。




View 端
section styles
  1. <style>
  2. label.error {
  3. color: red;
  4. }
  5.  
  6. .topGap {
  7. margin: 80px 0 0 0;
  8. }
  9.  
  10. .lblForTxt {
  11. margin-right: 10px;
  12. }
  13.  
  14. .gapBtwUI {
  15. margin-right: 10px;
  16. }
  17.  
  18. .peopleTable {
  19. border: 2px solid black;
  20. width: 600px;
  21. }
  22.  
  23. .peopleTable th, td {
  24. border: 2px solid black;
  25. }
  26.  
  27. .peopleTable th {
  28. background-color: navy;
  29. color: white;
  30. }
  31.  
  32. .fromServ th {
  33. background-color: #722F37;
  34. color: white;
  35. }
  36. </style>

html 主體
  1. <div class="row topGap">
  2. <div class="row">
  3. <h1>JSON Example</h1>
  4. <div class="bg-info">
  5. <p><i>Controller'll filter out people who r under 18yo.</i></p>
  6. </div>
  7. <table class="peopleTable fromServ">
  8. <caption>From Serv</caption>
  9. <tbody>
  10. <tr>
  11. <th>Name</th>
  12. <th>Age</th>
  13. </tr>
  14. @if (@Model != null)
  15. {
  16. foreach (var x in @Model)
  17. {
  18. <tr><td>@x.name</td><td>@x.age</td></tr>
  19. }
  20. }
  21. </tbody>
  22. </table>
  23. </div>
  24. <hr />
  25. <div class="row topGap">
  26. <label class="lblForTxt">Name:</label><input class="required gapBtwUI" type="text" name="txtName" value="someName" />
  27. <label class="lblForTxt">Age:</label><input class="required number gapBtwUI" type="text" name="txtAge" value="18" />
  28. <input type="button" id="add" class="gapBtwUI" name="add" value="add" onclick="addPerson()" />
  29. <input type="button" id="btn" name="btn" value="submit" />
  30. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "form1" }))
  31. {
  32. <input name="hdPeople" type="hidden" />
  33. }
  34. </div>
  35. <hr />
  36. <div class="row">
  37. <table id="peopleTable" class="peopleTable">
  38. <caption>Client input</caption>
  39. <tbody>
  40. <tr>
  41. <th>Name</th>
  42. <th>Age</th>
  43. <th></th>
  44. </tr>
  45. </tbody>
  46. </table>
  47. </div>
  48. </div>

section scripts
  1. <script type="text/javascript">
  2. // Add new row
  3. function addPerson() {
  4. var strOfNewRow = '<tr class="dataRow">';
  5. strOfNewRow += '<td>' + $('input[name="txtName"]').val() + '</td>';
  6. strOfNewRow += '<td>' + $('input[name="txtAge"]').val() + '</td>';
  7. strOfNewRow += '<td><input type="button" value="del" class="rowPerson" /></td>'
  8. strOfNewRow += '</tr>';
  9. $('.peopleTable tr:last').after(strOfNewRow);
  10. }
  11.  
  12. $(function () {
  13. // Remove row
  14. $(".peopleTable").on("click", ".rowPerson", function (e) {
  15. $(this).closest('tr').remove();
  16. });
  17. // Make input type btn instead of submit since we gonna convert table data before submit
  18. $('#btn').click(function () {
  19. // Turn table into an array
  20. var people = [];
  21. $('#peopleTable').find('tr.dataRow').each(function (i, el) {
  22. var $tds = $(this).find('td'),
  23. tmpName = $tds.eq(0).text(),
  24. tmpAge = $tds.eq(1).text();
  25. var tmpPerson = { name: tmpName, age: tmpAge };
  26. people.push(tmpPerson);
  27. });
  28.  
  29. // Convert javascript array to json format string and assgin to hiddenfield for form post
  30. var jsonStr = JSON.stringify(people);
  31. $('input[name="hdPeople"]').val(jsonStr);
  32.  
  33. // If u wanna use jquery submit like below, make sure there r no other tag named(or id as) sumbit.
  34. // Otherwise this method wont work
  35. $("#form1").submit();
  36. });
  37. });
  38. </script>

記得對應的 layout 加 js & css

在前端靠的是 json2 做轉換,從 script 區段你可以看到
  1. var jsonStr = JSON.stringify(people);
就一行,把 people 這個陣列轉換成需要的 JSON 字串。

而後端是使用
Newtonsoft.Json 下的 JsonConvert 進行反序列化
一樣只要短短一行
  1. var lst = JsonConvert.DeserializeObject<List<Person>>(hdPeople);
就能完成把 JSON 字串轉回 List 的格式。

最後順便一提 http://json2csharp.com/ 可以幫你把 JSON 轉成 C# 類別,吃別人 Src 的時候還蠻有用的。

ref: StackOverFlow
完整範例: GitHub

沒有留言:

張貼留言