顯示具有 C# MVC 標籤的文章。 顯示所有文章
顯示具有 C# MVC 標籤的文章。 顯示所有文章

2013年11月28日 星期四

MVC Razor 中 Replace BR

在ASP中,如果從資料庫中讀出資料,本來輸入的時候都是換行的,結果到畫面上都黏在一起,這時候都會用以下的語法來換行
1
replace(comment,"<br/>",vbcrlf>

在MVC中,因為是使用Razor語法,要換行要這樣寫

1
<span style="white-space: pre-line">@Html.DisplayFor(modelItem => item.Comment)</span>

2013年11月27日 星期三

MVC 建立 Partial View

Partial View 類似以前 ASP 的 include 頁面

建立方式如下

1. 在 View/Home 資料夾中建立一個 partialView.cshtml 的頁面,一開始裡面是空的
2. 在裡面輸入「我是  Partial View」
3. 在主頁面打入@{ Html.RenderPartial("partialView"); }

這樣就可以把頁面 include 進來了

2013年11月25日 星期一

MVC 變更尋找 View 的順序

MVC在找不到頁面的時候,會先找aspx、ascx...最後才會尋找cshtml
可以在Global.asax中加幾行程式,讓他先搜尋cshtml,可以加快搜尋速度


ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
ViewEngines.Engines.Add(new WebFormViewEngine());


















找不到檢視 'Index' 或其主版,或沒有任何檢視引擎支援搜尋的位置。已搜尋過下列位置:
~/Views/Home/_LayoutSample.cshtml
~/Views/Home/_LayoutSample.vbhtml
~/Views/Shared/_LayoutSample.cshtml
~/Views/Shared/_LayoutSample.vbhtml
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/_LayoutSample.master
~/Views/Shared/_LayoutSample.master

MVC4 更換主版頁面_Layout

原本的 Controller 是 return View();
變更為 return View("Index", "_LayoutSample",null);


2013年10月11日 星期五

【Web API】建立一個頁面,透過 Web API 來建立資料

1. 繼前一篇文章,可以取到資料後,來練習一下如何新增資料
http://tsengpm.blogspot.tw/2013/10/web-api-web-api.html


2. 其實好像也不難,只要 javascript 宣告一個一樣的 object,然後透過 JSON.stringify 轉成 Json 物件傳進去就好

3. 以下是程式碼

Javascript


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function AddData() {
 var product = {
  Id: document.getElementById('txtId').value,
  Name: document.getElementById('txtName').value,
  Category: document.getElementById('txtCategory').value,
  Price: document.getElementById('txtPrice').value
 };
 $.ajax({
  url: '/api/Products/PostProduct',
  type: 'POST',
  data: JSON.stringify(product),
  contentType: "application/json;charset=utf-8",
  success: function (data) {
   alert('新增成功');
   GetData();
  },
  error: function () {
   alert('新增失敗');
  }
 });
}

Html

1
2
3
4
5
<input type="text" id="txtId" value="" /><BR />
<input type="text" id="txtName" value="" /><BR />
<input type="text" id="txtCategory" value="" /><BR />
<input type="text" id="txtPrice" value="" /><BR />
<input type="button" id="btnAdd" value="新增資料" onclick="AddData();" />



【Web API】 建立一個讀取 Web API 的頁面

1. 練習寫一頁 Web ,從 Web API 讀取 Json 格式的資料,並顯示在當前的頁面上

2. 在 View 資料夾中,建立一個 View,取名「ReadWebAPI.cshtml」


3. 因為我的 View 是建在 Views\Home\ReadWebAPI.cshtml 下,所以 Controller\HomeController.cs 也要建一個對應的 method,View才能正常顯示












4.先試跑一下網頁,確定網頁可以正常執行



5.  因為是用 MVC4 ,預設就有 jQuery 可以使用了


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@section Scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("/api/Products", function (result) {
                var strHtml = "";
                strHtml += "<table>";
                for (var i = 0; i < result.length; i++) {
                    strHtml += "<tr>";
                    strHtml += "<td>";
                    strHtml += result[i].Id;
                    strHtml += "</td>";
                    strHtml += "<td>";
                    strHtml += result[i].Name;
                    strHtml += "</td>";
                    strHtml += "<td>";
                    strHtml += result[i].Category;
                    strHtml += "</td>";
                    strHtml += "<td>";
                    strHtml += result[i].Price;
                    strHtml += "</td>";
                    strHtml += "</tr>";
                }
                strHtml += "</table>";
                $("#Content").html(strHtml);
            })
            .error(function (res, textStatus, errorThrown) {
                alert("error ==> " + res.responseText);
            });
        });
    </script>
}
<p/>
<div id="Content"></div>

6. 結果顯示如下

【Web API】 回傳 json 格式

1. 繼上一篇文章, 回傳的是 xml,但是現在好像都用 json 比較多,所以改了一下,讓 Web API 也回傳 json
http://tsengpm.blogspot.tw/2013/10/crud-web-api.html

2. 在 Global.asax 中,加入一段程式

1
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();


3. 這樣就會回傳 json 了

【Web API】 建立一個具有 CRUD 功能的 Web API

1. 什麻是 CRUD?
ANS:Create / Read / Update / Delete
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations 


2. 開始建立專案,選擇ASP.NET MVC應用程式













3.  選擇Web API範本

















4. 在 Model 中新增一個類別,Product








1
2
3
4
5
6
7
public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
5. 在 Model 內新增一個Interface,IProductRepository

1
2
3
4
5
6
7
8
public interface IProductRepository
    {
        IEnumerable<Product> GetAll();
        Product Get(int id);
        Product Add(Product item);
        void Remove(int id);
        bool Update(Product item);
    }

6. 然後再新增一個類別,名叫 ProductRepository

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class ProductRepository : IProductRepository
    {
        private List<Product> products = new List<Product>();
        private int _nextId = 1;

        public ProductRepository()
        {
            Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M });
            Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M });
            Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
        }

        public IEnumerable<Product> GetAll()
        {
            return products;
        }

        public Product Get(int id)
        {
            return products.Find(p => p.Id == id);
        }

        public Product Add(Product item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            item.Id = _nextId++;
            products.Add(item);
            return item;
        }

        public void Remove(int id)
        {
            products.RemoveAll(p => p.Id == id);
        }

        public bool Update(Product item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            int index = products.FindIndex(p => p.Id == item.Id);
            if (index == -1)
            {
                return false;
            }
            products.RemoveAt(index);
            products.Add(item);
            return true;
        }
    }

7. 新增一個 Controller,ProductsController
 



8. 注意是繼承 ApiController



1
static readonly IProductRepository repository = new ProductRepository();

9. 撰寫 Read 的程式碼

 
1
2
3
4
 public IEnumerable<Product> GetAllProducts()
    {
        return repository.GetAll();
    }

10. 傳入id取得資料
1
2
3
4
5
6
7
8
9
public Product GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound); 
    }
    return item;
}

11. 新增資料
1
2
3
4
5
public Product PostProduct(Product item)
{
    item = repository.Add(item);
    return item;
}

12. 修改資料
1
2
3
4
5
6
7
8
public void PutProduct(int id, Product product)
{
    product.Id = id;
    if (!repository.Update(product))
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

13. 刪除資料
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public void DeleteProduct(int id)
{
 Product item = repository.Get(id);
 if (item == null)
 {
  throw new HttpResponseException(HttpStatusCode.NotFound);
 }

 repository.Remove(id);
}

14. 最後來測試一下資料,因為我的 Controller 叫做 ProductsController ,所以網址就會變成 http://XXXX/api/Products 

2013年9月8日 星期日

使用 MVC4 開發 SignalR Chat

參考文章:http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc-4

1. 新增一個MVC4的專案

2.  選「網際網路應用程式」

3.  在「套件管理主控台」,安裝SingalR

4. 輸入  install-package Microsoft.AspNet.SignalR

5.  之後檢查script底下,應該有SignalR的相關Script

6. 接下來新增一個Hubs的資料夾




7.  新增一個 SignalR Hub Class
 


8.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
using System;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}
9. 在 Global.asax 裡加入這一行

RouteTable.Routes.MapHubs();
 

10. 在「 Controllers/HomeController.cs」中新增一個 Chat 的 method
1
2
3
4
public ActionResult Chat()
{
    return View();
}

11. 在View >> Home 底下新增一個 Chat 的 View


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@{
    ViewBag.Title = "Chat";
}

<h2>Chat</h2>

<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion">
    </ul>
</div>

@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-1.0.1.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.--> 
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.  
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + htmlEncode(name) 
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}
12. 重點來了,按 F5 跑起來後,居然出現 執行階段錯誤: SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/hubs.



13.Google了好久,終於解決了

14.  在 BundleConfig.cs 中,加入 SignalR.js的 script, 另外因為IE解析 json 格式的問題,也要多加入 json2.js



















1
2
3
bundles.Add(new ScriptBundle("~/bundles/signalr").Include(
            "~/Scripts/json2.js", 
            "~/Scripts/jquery.signalR-{version}.js"));
15.  當然在 ~/Script 資料夾中,也要放入一個 json2.js 的檔案
可以在這邊取得: https://github.com/douglascrockford/JSON-js/blob/master/json2.js


16. 另外在 View/Home/Chat.cshtml中,修改一下 SignalR.js include的方式


1
@Scripts.Render("~/bundles/signalR")


17. 在按 F5執行一次,http://localhost:xxxx/home/chat,終於成功了


2011年11月5日 星期六

MVC 使用 Repository

1. 建立 MVC 專案

2. 可以看到 MVC 架構的資料夾都被建立起來了

3. 在 Models 資料夾建立新項目,選擇 「LINQ to SQL 類別」

4. 將資料表拉到畫面上

5. 在 Models 下建立一個 Interface,取名「IT0001Repository.cs」


    public interface IT0001Repository
    {
        List ListAll();
    }

6. 在 Models 下建立一個 Class,取名「T0001Repository.cs」,去實作 IT0001Repository


public class T0001Repository :IT0001Repository
    {
         private UUUDataContext _dataContext;

         public T0001Repository()
         {
             _dataContext = new UUUDataContext();
        }

         public List ListAll()
         {
            return _dataContext.T0001.ToList();
        }
    }

7.  在 Controls 下建立一個 Control ,取名「T0001Controller.cs」


 public class T0001Controller : Controller
    {
        //
        // GET: /T0001/
        IT0001Repository _repository ;

        public T0001Controller() : this(new T0001Repository()) { }

        public T0001Controller(T0001Repository repository)
        {
            _repository = repository;
        }

        public ActionResult Index()
        {
            return View(_repository.ListAll());
        }

    }

8. 以上大概都建置好了,現在要做最後一步,在 Views 下建立一個資料夾,取名「T0001」

9. 然後在 T0001 上按右鍵,加入 -> 檢視
   名稱取名「Index」,建立強型別檢視依圖設定,這樣會自動產生程式碼

10. 上面那個 View 取名 「Index」的原因,主要是在 Views -> Shared -> _Layout.cshtml
      我加了一行
  • @Html.ActionLink("T0001", "Index", "T0001")

  •       
          畫面上有一個名稱叫做T0001
          他會連結到 T0001資料夾下的Index檔案








    2011年7月2日 星期六

    【MVC】自建 HTML Helper

    1.新建一個資料夾,新增Class,取名ctlHelper.cs

    2.ctlHelper.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;




    namespace myApp.HTMLHelper
    {
        public static class ctlHelper
        {
            public static string LaberHelper(this HtmlHelper helper, string args)
            {
                return "
    " + args+ "
    ";
            }
        }
    }


    3.在 Views/*.aspx中引用
    <%=Html.LaberHelper("姓名") %>