0

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

tereško
  • 58,060
  • 25
  • 98
  • 150
Limey
  • 2,642
  • 6
  • 37
  • 62

1 Answers1

2

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

Community
  • 1
  • 1
Kerfuffle
  • 176
  • 11
  • The model doesn't have a method, I was adding that page_load into the aspx. – Limey Mar 20 '13 at 13:52
  • I was referring more to the Model.getAllRecords(). If you really want to get into MVC you might want to look at using .cshtml views instead of .aspx pages. If you set up a true Model (as a ViewModel class), View (as .cshtml), and Controller (as a Controller class) it becomes much easier to keep functionality separate. It also sets you up nicely for using asynchronous AJAX calls. If you have VS 2010 or 12 and want to see what I mean start a new MVC 3 web project with Razor view and look at the way it sets up. I recommend Razor as it simplifies, well... everything in your views. – Kerfuffle Mar 20 '13 at 16:01
  • Can't edit my last comment anymore, but I should correct the Model (as a ViewModel class) to just Model (as a separate class). I'm so used to my way of doing things (I have a base VM class that has properties I found myself using over and over) that I just put that in. I felt the need to clarify so as not to leave anyone reading that confused. – Kerfuffle Mar 20 '13 at 16:11
  • Thanks, I'm trying a new training course now that is showing me all this in MVC 4, so hopefully i get a better undering standing of the entire MVC process. – Limey Mar 20 '13 at 18:54