잊지 않겠습니다.

Data Binding : 규약을 이용하여 데이터 Entiry를 다루는 MVC Framework의 기능.

Model Binding
: HTML form의 submit시에 응용프로그램은 key/value pair로 폼의 데이터를 담고 있는 HTTP response를 받게 된다.
이때에, Http 요청 데이터를 Action method의 매개변수 및 사용자 정의 .NET 객체와 직접적으로 mapping하기 위한 알고리즘을 제공한다.

Model Binding 시의 데이터 적용 순서
1) Form(POST 매개변수 : FormCollection)
2) RouteData
3) QueryString

사용자 정의 형식에 대한 Model Binding
: 기본적으로 DefaultModelBinder는 {parameterName.PropertyName}으로 검색을 한다.
(* 대소문자는 가리지 않는다.)

다음과 같은 View가 존재한다고 할때에, 대응되는 ActionMethod는 다음과 같다.

1.<h1>New Product</h1>
2.<%=Html.ValidationSummary() %>
3.<%using(Html.BeginForm()) { %>
4.    Name : <%=Html.TextBox("productValue.name") %> <br>
5.    Price : <%=Html.TextBox("productValue.price")%> <br>
6.    Description : <%=Html.TextBox("productValue.description")%><br>
7.    <input type="submit" value="newProduct">
8.<%} %>

01.[AcceptVerbs(HttpVerbs.Post)]
02.public ActionResult New(Product productValue)
03.{
04.    try
05.    {
06.        productValue.CheckValidation();
07.    }
08.    catch(ProductException ex)
09.    {
10.        foreach(string key in ex.Keys)
11.        {
12.            ModelState.AddModelError(key, ex[key]);
13.        }               
14.        return View();
15.    }
16. 
17.    return RedirectToAction("NewResult",
18.        new { product = productValue });
19.}

BindAttribute의 이용
Bind Attribute는 Action Method의 매개변수 이름이 아닌 다른 이름으로 Binding을 원하거나, 특정 속성들이 모델 바인딩의 대상이 되어야하는지를 엄밀하게 제어할 필요가 있을 때 사용된다.

01./// <summary>
02./// 다음 ActionMethod는 productA.*, productB.* 로 prefix된 view의 id를 이용해서
03./// 값을 Binding한다.
04./// </summary>
05.[AcceptVerbs(HttpVerbs.Post)]
06.public ActionResult New([Bind(Prefix = "productA")] Product product1,
07.    [Bind(Prefix = "productB")]Product product2)
08.{
09. 
10.}
11./// <summary>
12./// 다음 ActionMethod는 Name과 Price를 Binding에 포함한다.
13./// </summary>
14./// <param name="product">
15./// <returns></returns>
16.public ActionResult RegisterMember([Bind(Include = "Name, Price")] Product product)
17.{
18. 
19.}
20./// <summary>
21./// 다음 ActionMethod는 DateOfBirthDay를 Binding하지 않는다.
22./// </summary>
23./// <param name="product">
24./// <returns></returns>
25.public ActionResult DeregisterMember([Bind(Exclude = "DateOfBirthDay")] Product product)
26.{
27. 
28.}
29. 
30.[Bind(Include="Name")]
31.public class Product
32.{       
33.    public string Name { get; set; }
34.    public string Price { get; set; }
35.    public string Description { get; set; }
36.}

Array, Collection, Dictionary에 대한 Model Binding
: 동일한 이름을 갖는 여러개의 Textbox를 Render하는 View의 Controller는 다음과 같이 사용될 수 있다.

01.<%=Html.TextBox("movies") %><br>
02.<%=Html.TextBox("movies") %><br>
03.<%=Html.TextBox("movies") %><br>
04. 
05.public ActionResult DoSomething(IList<string> movies)
06.{
07.    throw new NotImplementedException();
08.}
09.</string>


사용자 정의 Entry의 Group에 대해서는 다른 방법이 필요하게 되는데, DefaultModelBinder는 ActionMethod의 사용에 C#의 문법과 동일한 명명 규약을 따르기를 요구한다. 다음과 같은 ActionMethod가 존재할 때에, 사용되는 View는 다음과 같다.

01.public ActionResult DoSomething(IList<product> products)
02.{
03.    foreach(Product product in products)
04.    {
05.        System.Diagnostics.Debug.WriteLine(product.Name);
06.    }
07.    throw new NotImplementedException();
08.}
09. 
10. 
11.<%using(Html.BeginForm("DoSomething", "Products")) { %>
12.    <%for(int i = 0 ; i < 10 ; i++) { %>
13.        <h2><%=string.Format("Product : {0}", i) %></h2>
14.        <%--C#에서 사용되는 배열 문법과 동일하다.(products[0].Name, products[0].Price)--%>
15.        Name : <%=Html.TextBox("products["+i.ToString()+"].Name") %><br>
16.        Price : <%=Html.TextBox("products["+i.ToString()+"].Price") %><br>
17.        Description : <%=Html.TextBox("products["+i.ToString()+"].Description") %><br>           
18.    <%} %>
19.    <input type="submit" value="Submit Products">
20.<%} %>
21.</product>

사용자 지정 Model Binder의 지정
: 특정한 데이터에 대하여 사용자 지정 Model Binder를 사용하고 싶은 경우에는 IModelBinder interface를 상속한 사용자 지정 ModelBinder를 만들어주면 된다.



Model Binder가 사용되도록 구성하기 위해서 3가지 방법중 하나를 사용할 수 있다.
1) Model에 ModelBinderAttribute의 적용
[ModelBinder(typeof(XDocumentBinder))]
public class XDocument
{
    //...
}
2) ModelBinders.Binders.Add를 이용, 전역 ModelBinder에 등록하기
ModelBinders.Binders.Add(typeof(XDocument), new XDocumentBinder());
3) 매개변수를 Binding할때, Parameter attribute를 넣어주기
public ActionResult DoSomething([ModelBinder(typeof(XDocumentBinder))] XDocument xml)
{
    //...
}

.NET MVC Framework에서 ModelBinder Select 순위
1) Binding시에 명시적으로 지정된 Binder
2) 대상 형식을 위해 ModelBinders.Binders에 등록된 Binder
3) 대상 형식에 ModelBinderAttribute를 사용하여 할당된 Binder
4) DefaultModelBinder


Posted by Y2K
,