Limey
Limey

Reputation: 2772

databinding a Gridview in MVC

I'm trying to teach myself MVC, and i'm having issues with the code behind.

In my current issue, I'm trying to bind data to a gridview. Now, I have been able to do it by creating page_load method in my aspx.

<script language="CS" runat="server"> 
void Page_Load(object sender, System.EventArgs e)  
{
  grdMyGrid.DataSource = Model.getAllRecords();
  grdMyGrid.DataBind();
} 
</script>

This works, however, in my mind this can't be right. I have been forcing myself for the last year to make sure all binding are happening in the code behind, and all the MVC samples I have found show doing a databind in the aspx! (though they are all limited to textboxes). So what is the right method for doing this?

Thanks

Upvotes: 0

Views: 2695

Answers (1)

Kerfuffle
Kerfuffle

Reputation: 176

There are a few items here. In an ideal world via MVC your model should just be a holder for data. I.E. No methods, logic, etc. That should all be handled by your controller. (I highly recommend reading articles/entries in K. Scott Allen's blog at odetocode.com to learn about proper use of MVC). That said, I have to inquire as to why the model has a method.

More to your question though: MVC pages really, really shouldn't be using web forms and the controls therein. I'm just going to link to this question for that: How to use gridView in Mvc without adding form runat server?

The accepted answer there lists one way to handle this, and another option is to use a display template, for which you can find a decent tutorial here: http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx

Upvotes: 2

Related Questions