NancyFx框架中使用綁定模型 新建一個空的Web程式 然後安裝Nuget庫裡面的包 Nancy Nancy.Hosting.Aspnet Nancy.ViewEnglines.Spark 併在Web應用程式裡面添加Models,Module,Views三個文件夾 繼續往Models文件夾裡面添加 ...
NancyFx框架中使用綁定模型
新建一個空的Web程式
然後安裝Nuget庫裡面的包
- Nancy
- Nancy.Hosting.Aspnet
- Nancy.ViewEnglines.Spark
併在Web應用程式裡面添加Models,Module,Views三個文件夾
繼續往Models文件夾裡面添加Database,ModelBinders
然後往Models文件夾裡面添加Customer類
public int Id { get; set; } public string Name { get; set; } public DateTime RenewalDate { get; set; }
繼續往Models文件夾裡面添加Event類
public int Id { get; set; } public string Title { get; set; } public string Location { get; set; } public IEnumerable<int> Venues { get; set; } public DateTime Time { get; set; } public Event() { this.Title = "Lexan"; this.Location = "Lexan"; this.Time = DateTime.Now; }
繼續往Models文件夾裡面添加User類
public string Name { get; set; } public string Address { get; set; }
然後往Database文件夾裡面添加DB類
public static List<Event> Events { get; private set; } public static List<Customer> Customer { get; private set; } static DB() { Events = new List<Models.Event>(); Customer = new List<Models.Customer>(); }
然後往ModelBinders文件夾裡面添加CustomerModelBinder類
//是否可以綁定到給定的模型類型 public bool CanBind(Type modelType) { return modelType == typeof(Customer); } //綁定到給定的模型類型 public object Bind(NancyContext context,Type modelType, object instance,BindingConfig configuration,params string[] blackList) { var customer = (instance as Customer) ?? new Customer(); customer.Name = customer.Name ?? context.Request.Form["Name"]; customer.RenewalDate = customer.RenewalDate == default(DateTime) ? context.Request.Form["RenewalDate"] : customer.RenewalDate; return customer; }
然後往Module里添加MainModule類
public MainModule() { Get("/", Lexan => { return "<a href='/events'>Events (預設模型綁定)</a><br><a href='/customers'>Customers (自定義模型綁定)</a><br><a href='/bindjson'>Users (JSON)</a></a><br><a href='/bindxml'>Users (XML)</a><br>"; }); }
然後往Module里添加CustomersModule類
public CustomersModule() : base("/customers") { Get("/",Lexan=> { var model = DB.Customer.OrderBy(e=>e.RenewalDate).ToArray(); return View["Customers",model]; }); Post("/",Lexan=> { Customer model = this.Bind(); var models = this.Bind<Customer>(); DB.Customer.Add(model); DB.Customer.Add(models); return this.Response.AsRedirect("/Customers"); }); }
然後往Module里添加EventsModule類
public EventsModule():base("/events") { Get("/",Lexan=> { var model = DB.Events.OrderBy(x=>x.Time).ToArray(); return View["Events",model]; }); Post("/",Lexan=> { Event model = this.Bind(); var models = this.Bind<Event>("Location"); DB.Events.Add(model); DB.Events.Add(models); return this.Response.AsRedirect("/Events"); }); }
然後往Module里添加JsonModule類
public JsonModule() { Get("/bindjson",Lexan=> { return View["PostJson"]; }); Post("/bindjson",Lexan=> { User model = this.Bind(); var sb = new StringBuilder(); sb.AppendLine("綁定模型:"); sb.Append("類型:"); sb.AppendLine(model.GetType().FullName); sb.Append("名字:"); sb.AppendLine(model.Name); sb.Append("地址:"); sb.AppendLine(model.Address); return sb.ToString(); }); }
然後往Module里添加XmlModule類
public XmlModule() { Get("/bindxml",Lexan=> { return View["PostXml"]; }); Post("/bindxml",Lexan=> { var model = this.Bind<User>(x=>x.Name); var sb = new StringBuilder(); sb.AppendLine("綁定模型:"); sb.Append("類型:"); sb.AppendLine(model.GetType().FullName); sb.Append("名字:(這將是空的, 因為它被忽略)"); sb.AppendLine(model.Name); sb.Append("地址:"); sb.AppendLine(model.Address); return sb.ToString(); }); }
然後往根目錄裡面添加Bootstrapper類
然後往Views文件夾裡面添加Customers.txt文件
然後把Customers.txt改成Customers.spark
添加如下內容
<viewdata model="ModelBindingDemo.Models.Customer[]"/> <html> <head> <title>客戶</title> </head> <body> <h1>客戶</h1> <p>客戶被添加了兩次, 一個使用動態活頁夾適配器, 另一個使用通用的.</p> <p>當前客戶:</p> <ul> <li each="var v in Model"> <a href="customer/${v.Id}"> ${v.Name} - ${v.RenewalDate.ToShortDateString()} </a> </li> </ul> <h2>添加另一個</h2> <form method="POST" action="/customers"> <label for="Name">名字</label> <input type="text" name="Name" /> <label for="Location">更新日期</label> <input type="text" name="RenewalDate" /> <input type="submit"/> </form> </body> </html>
同樣的做法添加Event.txt添加成功後改成Event.spark
並添加如下內容
<viewdata model="ModelBindingDemo.Models.Event[]"/> <html> <head> <title>事件</title> </head> <body> <h1>事件</h1> <p>事件被添加兩次, 一個使用動態活頁夾適配器, 另一個使用通用的.</p> <p>第二個有 ' 位置 ' 標記為黑名單, 因此應該顯示為 ' 預設 '</p> <p>當前事件:</p> <ul> <li each="var v in Model"> <a href="event/${v.Id}"> ${v.Title} - ${v.Location} </a> ${v.Time} </li> </ul> <h2>Add another</h2> <form method="POST" action="/events"> <label for="Name">標題</label> <input type="text" name="Title" /> <label for="Location">位置</label> <input type="text" name="Location" /> <input type="checkbox" name="Venues" value="1">地點 1</input> <input type="checkbox" name="Venues" value="2">地點 2</input> <input type="checkbox" name="Venues" value="3">地點 3</input> <input type="checkbox" name="Venues" value="4">地點 4</input> <label for="EventDate">時間</label> <input type="text" name="Time" value="${System.DateTime.Now}"/> <input type="submit"/> </form> </body> </html>
然後繼續再Views文件夾裡面添加PostJson.html
<html> <head> <title>JSON Post Test</title> <script type="text/javascript"> $(function () { var dat = "{\"Name\":\"This is the name\", \"Address\":\"This is the address\"}"; alert("將以下數據粘貼到 /bindjson:\n\n" + dat); $.ajax({ type: "POST", url: "/bindjson", contentType: "application/json", data: dat, success: function (data) { alert("Response:\n" + data); } }); }); </script> </head> <body> JSON Post </body> </html>
繼續添加PostXml.html頁面
<html> <head> <title>XML Post Test</title> <script type="text/javascript"> $(function () { var dat = "<User><Name>這是名字</Name><Address>這是地址</Address></User>"; alert("將以下數據粘貼到 /bindxml:\n\n" + dat); $.ajax({ type: "POST", url: "/bindxml", contentType: "application/xml", data: dat, success: function (data) { alert("Response:\n" + data); } }); }); </script> </head> <body> XML Post </body> </html>
最後修改Web.config配置文件
<httpRuntime targetFramework="4.5.2"/> <httpHandlers> <add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" /> </httpHandlers> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <validation validateIntegratedModeConfiguration="false" /> <handlers> <add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" /> </handlers> </system.webServer>
現在我們看看運行的結果
到這裡就結束了,感謝你的欣賞,這篇也算介紹完了NancyFx2.0版本的基本使用,後期看看如果有空的話會繼續更新,我們不見不散,哈哈哈!