본문 바로가기

.NET/MVC.NET

WebGrid 에서 선택된 Row 가져오기

MVC3에 WebGrid의 선택된 Row를 가져오기를 따라해 보겠습니다. 순서대로 하시면 됩니다.

1.모델 만들기.
 public class Person
    {
        public int Id { getset; }
        public string GivenName { getset; }
        public string Surname { getset; }
        public int Age { getset; }
 
        public static List<Person> GetPeople()
        {
            return new List<Person>
                       {
                           new Person { Id = 1, GivenName = "김", Surname = "11", Age = 11 },
                           new Person { Id = 2, GivenName = "김", Surname = "22", Age = 22 },
                           new Person { Id = 3, GivenName = "김", Surname = "33", Age = 33 }
                       };
        }
    }

2.  View

@model IEnumerable<MvcApplication1.Models.Person>
@{
    WebGrid grid = new WebGrid(Model, selectionFieldName: "SelectedRow");
    @grid.GetHtml(
        columns: grid.Columns(
            grid.Column("Edit", header: null, format: @<text>@item.GetSelectLink("Edit")</text>),            
            grid.Column("Firstname", format: @<text>@item.GivenName</text>),
            grid.Column("Surname", format: @<text>@item.Surname</text>),
            grid.Column("Age", format: @<text>@item.Age</text>)
        )
    )


첫번째 컬럼이 이작에 키포인트 입니다. @item.GetSelectLink("Edit") 는 선택된 Row의 A태그를 렌더링 해 주고
WebGrid생성자 함수에서 셋팅한 SelectedRow로 QueryString을 생성합니다.

@if (grid.HasSelection)
{
	var person = grid.SelectedRow ;
	Response.Write(person.ToArray()[2]);
}

위의 View코드의 연장입니다.
실제적으로 Selection이 일어날때 확인할수 어떤일이 일어나는지 확인할수 있습니다.