2017年5月1日 星期一

Asp.net MVC - View傳遞資料給Controller

QueryString

  • 在網址後加上參數名稱和參數值
  • ?name1=value1&name2=value2&...


Form表單

  • 透過form及submit將form裡的參數送至controller,處理少量參數
  • 範例:
Action: 
public ActionResult  ModelBind(string name)
{
    ViewBag.Name=name;
    return View();
}
View : 
<form action="/cont/ModelBind" method="post">
     Name:<input type="text" name="name"/>
    <input type="submit" value="Submit" />
</form>
<p>Your Name : @ViewBag.Name</p>
  • FormCollection類別,處理傳遞多個參數
  • 範例:
Action: 
public ActionResult  ModelBind(FormCollection form)
{
    ViewBag.Name=form["name"];
    ViewBag.Age=form["age"];
    return View();
}
View : 
<div> 
@using(Html.BeginForm()){
     Name:<input type="text" name="name"/><br/>
     Age: <input type="text" name="age"/><br/>
    <input type="submit" value="Submit" />
}
</div> 
<p>
 Your Name : @ViewBag.Name<br/>
 Your Name : @ViewBag.Age
</p>



RouteData

  • 透過路由範本取得參數值
  • /{Controller}/{Action}/{id}


JSON
  • 範例:
Model:
 public class Person
{
    public string id {get;set;}
    public string name  {get;set;} 
    public string email {get;set;} 
} 


Action:
[HttpPost]
public ActionResult ExJson(Person[] p)
{
    return Json(p, JsonRequestBehavior,AllowGet); 
} 




2017年4月27日 星期四

Asp.net MVC - Controller傳遞資料給View-2

多個Model(物件)


  • 透過LINQ的Include方法與Lambda Expression將相關聯的資料(關聯資料表),由多個物件封裝成一個
  • 範例:
Action:
public ActionResult ExInclude()
{ 
var courses = db.Courses     
.Include(c=>c.Students)     
.Include(c=>c.Schedule) 
return View(courses.ToList());
}
View:
@model IEnumerable<Courses>
<!--標題-->
<tr>
<th>@Html.DisplayNameFor(model=>model.courseName)</th><th>@Html.DisplayNameFor(model=>model.Students.studentID)</th><th>@Html.DisplayNameFor(model=>model.Schedule.classTime)</th>
</tr> 
<!--內容--> 
@foreach(var item in Model){
<tr>
<td>@Html.DisplayFor(modelItem=>model.courseName)</td><td>@Html.DisplayFor(modelItem=>model.Students.studentID)</td><td>@Html.DisplayFor(modelItem=>model.Schedule.classTime)</td>
</tr>
}

ViewModel

  • 專門給View使用的Model物件資料
  • 可以將無相關聯的資料封裝成一個
  • 將所需的多個物件透過一層Class進行屬性封裝
  • 新增ViewModels目錄,通常放在Models目錄之下
  • 範例:
Class:

public class Books
{
public string bookID {get;set;}
public string bookName {get;set;}
public IEnumerable<Order> Order {get;set;}
}
public class Order
{
public string orderNo {get;set;}
public string orderDate {get;set;}
public string orderNumber {get;set;}
}

Action:
public ActionResult ExViewModel()
{
    List<Order> orders = new List<Order>();
    orders.Add(new Order
    {
        orderNo="0001",
        orderDate="2017-04-26",
        orderNumber=2
    });
    orders.Add(new Order
    {
        orderNo="0002",
        orderDate="2017-04-27",
        orderNumber=3
    });
    Books books = new Books();
    books.bookID = "A123456";
    books.bookName = "MVC WOW";
    books.Order = orders;
    return View(books);
}
 View:

@model Books
Book ID: @model.bookID
Book Name: @model.bookName
Order:
<table>
    <tr>
        <th>Order NO</th>
        <th>Order Date</th>
        <th>Order Number</th>
    </tr>
 @foreach(var item in model.Order)
{
    <tr>
        <td>item.orderNO</td>
        <td>item.orderDate</td>
        <td>item.orderNumber</td>
    </tr>
}
</table> 
JSON


    • 使用JavaScriptSerializer類別進行序列化工作,回傳時會設置ContentType為application/json
    • 範例:
    • Model:
       public class Person
      {
          public string id {get;set;}
          public string name  {get;set;} 
          public string email {get;set;} 
      } 


      Action:
      public ActionResult ExJson()
      {
           Person person = new Person{ id="A001", name="isabella",email="a@b.c"};
          return Json(person, JsonRequestBehavior,AllowGet); 
      } 

    2017年4月26日 星期三

    Asp.net MVC - Controller傳遞資料給View-1

    ViewData

    • ViewDataDictionary字典型別
    public class ViewDataDictionary : IDictionary<string, object>()
    • key必須是字串,內容可儲存任何物件資料 。
    • 無法跨Action方法存取,只能存在於此次HTTP Request中。 
    • 範例:

    Action: 
    public ActionResult ExViewData()
    {
    //Key: Name, data: Isabella
    ViewData["Name"] = "Isabella";
    return View();
    }
    View:
    <h2>ExViewData</h2>
    Name:
    @ViewData["Name"] 

    ViewBag
    • dynamic型別
    • 略過編譯時期靜態型別檢查,改在執行階段進行,大部分行為就像object型別一樣。
    • 效能會比ViewData差一點點。
    • 無法跨Action方法存取,只能存在於此次HTTP Request中。 
    • 範例:
    Action: 
    public ActionResult ExViewBag()
    {
    //Key: Name, data: Isabella
    ViewBag.Name = "Isabella";
    return View();
    }
    View:
    <h2>ExViewBag</h2>
    Name: 
    @ViewBag.Name

    TempData
    • TempDataDictionary字典型別
    public class TempDataDictionary : IDictionary<string, object>()
    • 將資料放在Session之中,所以具有跨Action、Controller存取的能力。
    •  一旦資料被取出,就會被刪除,若不想被刪除的話需要用keep()將資料保存。
    TempData.Keep();
    • 範例:
    第一個Controller:
    public class FirstController : Controller
    {    
    // GET: First    
    public ActionResult Index()    
    {        
    TempData["Name"] = "Isabella";        
    return new RedirectResult(@"~\Second\");//轉到第二個Controller    
    }
    }
    第二個Controller:
    public class SecondController : Controller
    {    
    // GET: Second    
    public ActionResult Index()    
    {        
    return View();    
    }
    }
    第二個Controller的View:
    <h2>ExTempData</h2>
    Name: @TempData["Name"]




    2016年4月15日 星期五

    AngularJS範例說明9-routing mode


    • 標籤模式
      • Hash URL, URL路徑會以#符號開頭。
      • 與config函數中的$routeProvider進行配置。
        <!--標籤模式-->

    <div class="pull-left">
          <span><a href="#/">Default Route</a></span>
        </div>
        <div class="pull-right">
          <span ng-hide="mainCtrl.userService.isLoggedIn">
            <a href="#/login">Login</a>
          </span>
          <span ng-show="mainCtrl.userService.isLoggedIn">
            <!-- server-side route, not a client-side route -->
            <a href="/api/logout">Logout</a>
          </span>
        </div>

    <script type="text/javascript">
        angular.module('myApp', ['ngRoute'])
        .config(function ($routeProvider) {
            $routeProvider
            .when('/', {
                templateUrl: 'views/home.html',
                controller: 'HomeController'
            })
            .when('/login', {
                templateUrl: 'views/login.html',
                controller: 'mainCtrl'
            })
            .when('/api/logout', {
                templateUrl: 'views/logout.html',
                controller: 'mainCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });

        });
        </script>


    • HTML5模式
      • URL看起來與一般server side route無異。
      • 啟用HTML5模式
        • $locationProvider.html5Mode(true)
        • index.html增加含有herf屬性的<base>標籤來告知瀏覽器相關URL的所在位置
        • server side支援url重寫,並確保所有請求都返回index.html(nodejs)
        <!--HTML5模式-->

    <html>
      <head>
        <base herf="/app" />
        <title>HTML5 Mode</title>
      </head>
      <body>
        <script type="text/javascript">
            angular.module('myApp', ['ngRoute']).
            config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
                $locationProvider.html5Mode(true);
                $routeProvider
                .when('/', {    //指到<base>設定的地方=>即為/app
                    templateUrl: 'views/home.html',
                    controller: 'HomeController'
                })
                .otherwise({
                    redirectTo: '/'
                });
            }]);
        </script>
      </body>
    </html>

    AngularJS範例說明8-ng-view、ngRoute、$routeProvider

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js"></script>
        <!--1. include angular-route.js in your HTML-->
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.js"></script>
        <title></title>
        <meta charset="utf-8" />
    </head>
    <body ng-app="myApp">

        <!--2. ng-view是由ngRoute提供的一個特殊指令,是routing後視圖模板的作用域-->
        <div ng-view></div>

        <script type="text/javascript">
            //3. load the module in your application
            angular.module('myApp', ['ngRoute']).
            //4. Config區塊使用$routeProvider定義routes
            config(['$routeProvider', function ($routeProvider) {
                $routeProvider
                //AngularJS提供的when和otherwise兩個方法來定義應用的路由
                /*使用when來添加一個特定路由,此方法可以添加兩個參數:when(path, route)
                ex:
                    $routeProvider.when(url,{
                        template:string,
                        templateUrl: string,
                        controller: string, function or array,
                        controllerAs: string,
                        redirectTo: string or function,
                        reloadOnSearch: true or false,
                        resolve: object<key, function>
                    });

                    path:路由路徑,與$location.path(即為當前的URL路徑)進行匹配。可用$routeParams讀取這個參數
                    route:配置對象。當路徑匹配成功時,具體該做些什麼。其中屬性包含了controller、template、templateURL、resolve、redirectTo和reloadOnSearch

                        *controller
                            controller: 'MyController'
                            controller: function($scope) {}
                        *template
                            template: '<div><h2>Route</h2></div>'
                        *templateURL
                            templateUrl: 'views/template_name.html'
                        *redirectTo
                            redirectTo: '/home'
                            redirectTo: function(route,path,search)
                        *reloadOnSearch
                            reloadOnSearch:true(default)
                            reloadOnSearch:false
                            當$location.search()或$location.hash()發生變化時會重新加載路由。
                        *resolve
                            載入特定route前,預先執行一個非同步工作
                */
                .when('/', {
                    templateUrl: 'views/home.html',
                    controller: 'HomeController'
                })
                .when('/temp', {
                    template: '<h5>This is template route.</h5>',
                    controller: 'TempController'
                })
                .when('/login', {
                    templateUrl: 'views/login.html',
                    controller: 'LoginController'
                })
                .when('/dashboard', {
                    templateUrl: 'views/dashboard.html',
                    controller: 'DashboardController',
                    resolve: {
                        user: function (SessionService) {
                            return SessionService.getCurrentUser();
                        }
                    }
                })
    //使用otherwise來定義預設路由
                .otherwise({
                    redirectTo: '/'
                });
            }]);
        </script>
    </body>
    </html>