模型綁定支持字段或屬性兩種方式,使用模型綁定,能夠經過下面的方式實現綁定:git
// Properties public class Model{ public int Value { get; set; } }
// Fields public class Model{ public int Value; }
每一個類有本身的參數方式。使用屬性意味着你須要後續的操做中使用數據驗證或者加強的功能,你的代碼已經經過get
訪問器調用一個方法, 而且你能夠改變這個方法的實現。 換一種說法, 當屬性沒有明確的使用方式 (就像上面示例中的-- 沒有提供實際的 get
和set
訪問器), C# 編譯器根據名稱經過隱含的操做自動地獲取對應字段的值。 這個字段名須要惟一,以防止和其它成員名衝突。爲了實現這個目的,不可以使用的C#特殊標識符。特別地如包含了尖括號。若是數據類型使用了 DataContractSerializer
, 將會引起這個結果,由於 DataContractSerializer
操做針對字段,而不是屬性。它會使用相同的名字獲取字段和嘗試建立XML元素。由於XML元素不能包括 <
和>
字符,將會引起異常, 在內部的處理會對字段名進行轉義。 (異常能夠在運行使用DataContractSerializer的程序時經過調試輸出查看,常見的狀況一般是默認WCF綁定配置中。) 異常和轉換並非必需要執行,你能夠經過使用符合的XML標識的字段避免它。github
除非你的項目有外部組件引用了它,你使用那種方式可有可無,由於大多數.net訪問屬性和字段的語法徹底相同的。所以,在大多數狀況下, 你能夠更改你的模型類型,使用屬性或者字段,編譯時無需作其餘修改。數組
對於自動模型綁定到複選框的布爾值,肯定設置了value="true"
在複選框中。dom
<input type="checkbox" name="rememberMe" value="true"/>
public class LoginModel{ public bool RememberMe; }
Nancy支持服務端提交列表形式的東東而且綁定他們,就像以前使用this.Bind<T>()的方式。async
Nancy使用兩種方式支持綁定列表項(或者數組及其餘能夠實現可枚舉的類型),做爲你綁定到的那個對象的列表或通用對象的列表。ide
若是你有相似下面的表單:post
<form action="/ArrayOnObject" method="post"> <input type="text" name="Tags" value="Tag1,Tag2,Tag3"/> <input type="text" name="Ints" value="1,2,3,4,4,5,6,3,2,21,1"/> <input type="submit" value="Submit"/> </form>
你能夠綁定到下面的類:ui
public class Posts{ public string[] Tags; public int[] Ints; }
使用這樣的語句:this
var listOfPosts = this.Bind<Posts>();
Imagine you have a system to enter who commits the most to a OSS-framework. You allow the users of the site to post a bunch of users-names and their number of commits at once.spa
Here's an example form with random dummy data:
<form action="/SimpleListDemo" method="post"> User 1:<input type="text" name="Name[0]" value="thecodejunkie" /> Commits <input type="text" name="Commits[0]" value="1068"/> <br /> User 2:<input type="text" name="Name[1]" value="grumpydev" /> Commits <input type="text" name="Commits[1]" value="1049"/> <br /> User 3:<input type="text" name="Name[2]" value="jchannon" /> Commits <input type="text" name="Commits[2]" value="109"/> <br /> User 4:<input type="text" name="Name[3]" value="prabirshrestha" /> Commits <input type="text" name="Commits[3]" value="75"/> <br /> User 5:<input type="text" name="Name[4]" value="phillip-haydon" /> Commits <input type="text" name="Commits[4]" value="40"/> <br /> <input type="submit" value="Test the binding thingy"/> </form>
This can then be bound (with this.Bind<List<User>>();
) to a list of object of this class:
public class User{ public string Name; public int Commits; }
Nancy supports two kind of list delimiters for the name of the items in the HTML-form;
underscores (Name_1
, Name_2
etc.)
brackets (Name[1]
, Name[2]
etc.)
Here's an end-to-end model binding example that shows the full model + view + module.
/// <summary> /// DTO for creating a new user /// </summary> public class NewUser { public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } }
ViewBag.Title = "AkkaChat - Register"; } @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<AkkaChat.ViewModels.NewUser> <div class="container-fluid"> <div class="row-fluid"> <h1>Register an AkkaChat Account</h1> @if (ViewBag.ValidationError != null) { <div class="alert-error"> <p>Error! @ViewBag.ValidationError</p> </div> } <form class="form-horizontal" method="POST" action="~/register"> <div class="control-group"> <label class="control-label" for="UserName">Username</label> <div class="controls"> <input type="text" name="UserName" id="UserName" placeholder="Username"> </div> </div> <div class="control-group"> <label class="control-label" for="Email">Email</label> <div class="controls"> <input type="text" id="Email" name="Email" placeholder="Email"> </div> </div> <div class="control-group"> <label class="control-label" for="Password">Password</label> <div class="controls"> <input type="password" name="Password" id="Password" placeholder="Password"> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn">Register</button> </div> </div> </form> </div> </div>
/// <summary>/// Module responsible for handling authentication and account creation/// </summary>public class AuthModule : NancyModule{ private readonly IMembershipService _membership; public AuthModule(IMembershipService membership) { _membership = membership; Get["/register"] = _ => { //already logged in if (Context.CurrentUser.IsAuthenticated()) return Response.AsRedirect("~/"); return View["register"]; }; Post["/register", true] = async (x, ct) => { NewUser registerAttempt = this.Bind<NewUser>(); //model binding! var validationError = ""; var failedValidation = false; if (string.IsNullOrEmpty(registerAttempt.UserName)) { failedValidation = true; validationError += string.Format("Must provide a username!<br>"); } else { //check to see if a username is available var userNameAvailable = await _membership.IsUserNameAvailable(registerAttempt.UserName); if (!userNameAvailable) { validationError += string.Format("{0} is already taken. Please pick another username.<br>", registerAttempt.UserName); failedValidation = true; } } if (string.IsNullOrEmpty(registerAttempt.Password)) { failedValidation = true; validationError += string.Format("Must provide a password!<br>"); } if (string.IsNullOrEmpty(registerAttempt.Email)) { failedValidation = true; validationError += string.Format("Must provide an email!<br>"); } if (failedValidation) { ViewBag.ValidationError = validationError; return View["register"]; } var registerResult = await _membership.AddUser( registerAttempt.UserName, registerAttempt.Email, registerAttempt.Password); //success! if (!(registerResult is MissingUserIdentity)) { return this.LoginAndRedirect(registerResult.CookieId, DateTime.Now.AddDays(30), "~/"); } else //failure! { ViewBag.ValidationError = string.Format("Unable to register as {0} - server error.", registerAttempt.UserName); return View["register"]; } }; } }