Pergunta

How do we use strongly-typed Model Binding with GridView's BoundField? The DataField attribute of BoundField seems to take a string value only, unlike FormView where I can use the proper Model Binding syntax like Prop="<%# MyFieldName %>". Is TemplateField my only option here?

Foi útil?

Solução

For any future reader, TemplateField is your only choice if you want to take advantage of strongly-typed binding and intellisense etc.

Outras dicas

I am not sure what you want but still I have created a small app like this.

Here is gridview in aspx page.

 <asp:GridView runat="server" ID="grdEmployee" AutoGenerateColumns="False"  ModelType="WebApplication1.Employee">
       <Columns>
           <asp:BoundField DataField="Age" HeaderText="Age"/>
           <asp:BoundField DataField="Name" HeaderText="Name"/>
       </Columns>
   </asp:GridView> 

Now I have created Employee class like following.

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
}

and in page_load event of asp.net I am writing this.

protected void Page_Load(object sender, EventArgs e)
    {
        List<Employee> employees=new List<Employee>();
        Employee employee=new Employee{Age = 33,Name = "Jalpesh Vadgama"};
        employees.Add(employee);

        employee = new Employee { Age = 30, Name = "Vishal Vadgama" };
        employees.Add(employee);

        grdEmployee.DataSource = employees;
        grdEmployee.DataBind();
    }

and it's works. For two way binding you need to use template control with bindItem.

Reference- http://www.sitepoint.com/asp-net-4-5-strongly-typed-data-controls-model-binding/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top