I’m following a tutorial on creating the NerdDinner using ASP.Net MVC. However, I’m using Visual Studio 2010 Ultimate edition and there was only MVC2 to choose from.
So I’ve following the tutorial so far, and everything is really clicking and being really well explained, until this little hitch.
The guide is asking me to create new methods on a Controller file like so:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NerdDinner.Controllers
{
public class DinnersController : Controller
{
public void Index(){
Response.Write("<h1>Coming Soon: Dinners</h1>");
}
public void Details(int id) {
Response.Write("<h1>Details DinnerID: " + id + "</h1>");
}
}
}
However, when I created the Controllers file, Visual Studio created an Index method already, but it looks vastly different to what the tutorial shows. Maybe this is the new way to do things using MVC2?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NerdDinner.Controllers
{
public class DinnersController : Controller
{
//
// GET: /Dinners/
public ActionResult Index()
{
return View();
}
}
}
My question is, how can I reproduce the Details and Index method (they’re in MVC) to the MVC2 way?
Is this even relevant? Thank you!
The latter way is correct, all HTML output should go through a View unless you are doing something exceptional. I am surprised that the book is telling you to use voids for Actions. This is not new to MVC2, I think maybe there is something wrong in the book!
Actions have a return type of ActionResult, which is really just a generic base type that might be HTML, a redirect, or a file download.
View() is a method on Controller. It will automatically look for a View with the same name as your Action. So DinnersController.Index() will return the view located at Views/Dinners/Index.aspx.
In fact, if you right-click on the word View() it will give you the option to add a new view and put it in the right place. The view is where your HTML should be.