Menu

Starting Out With ASP.NET MVC Part 2

Starting Out With ASP.NET MVC Part 2

Last time I left off with ASP.NET MVC, I covered how to create a new MVC project in Visual Studio and how to add new Controllers and Views. I was able to show how to pass data to the View from the Controller using the ViewBag and how to render Views from the Controller. I covered the VC part and purposely left out the M, the Model. So in this post, I am going to be adding a Model to the project and I will be using the Entity Framework as the ORM in order to access the data. I'm not a huge fan of the Entity Framework, mainly because it ties the code and the data too closely together, and sometimes with complex queries, you end up with super complex expressions in your code in order to retrieve data, and that kind of defeats the purpose of separation of concerns.


Let's add a model


I'll start off by adding a model to the project. And we can do that as easily as we add anything else. Right click on the Models directory and add a new class.

I'm going to be using EF's code-first paradigm, which means that my database will be generated based on the class that I just created. I'll make a simple class, one that probably everybody has seen before.



public class Movie
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}


This class will in turn become our database table and each of the properties a database column. Any changes to the model will propagate over to the database, which is convenient particularly on new projects in which the data model has a higher chance of changing.


Entity Framework(EF) and the DbContext


Before I can communicate with the database however, I need to define a database context, which Entity Framework provides and which will represent our database and will allows us to perform the many different database operations, like inserting and selecting.



public class Movie
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

public class MovieDBContext : DbContext
{
    public DbSet Movies { get; set; }
}


The MovieDBContext derives from the DbContext base class provided by the Entity Framework and it is responsible for keeping our data synced between model and the database. The DbSet property inside of our newfound class will represent a collection of records of the type we specify.


Set up connection string


The DbContext will handle the mapping of objects to database records, however, it still needs to be told which database in particular it will be connecting too. And we do by specifying the connection string in the web.config. In EF, the name of the connection string must match the name of the DbContext class, in the example above that would be MovieDBContext. However, this is an optional step and if no connection string is provided then EF will use the default one that is provided by default in the web.config.


Let's get some data


Now that we have our piping and configuration out of the way, we can get to grabbing some data. For this step, I'll be using some of the built in scaffolding capabilities that Entity Framework provides. I'm going to add a new Controller which will handle the basic database operations such as inserting, updating and deleting.

So let's create a new Controller and select the "MVC 5 Controller with views, using Entity Framework" option. And configure it like the following:

It's somewhat self explanatory. You select the model that you want to create a CRUD for and you select the context that we created up above. And thanks to the scaffolding capabilities, we should automatically have the required Views created for us in our solution explorer.

Visual Studio went ahead and created all of our basic Create/Read/Update/Delete Views for us. The automatic creation of CRUD action methods and views is known as scaffolding.


Sending data to the View


If we weren't using the built-in scaffolding features of Entity Framework, we'd still have to do the exact same work ourselves, so let's take a look at how that's done. Instead of going through each of the Views and how they work however, I'll give a general overview of sending data to Views in ASP.NET MVC. I showed in part 1 of this tutorial how you can use the ViewBag to store any type of data and pass it over to the View from the Controller. And if we wanted to, we can just as easily stick a Movie object into the ViewBag and work with that.



private MovieDBContext db = new MovieDBContext();

public ActionResult Details(int? id)
{
        Movie movie = db.Movies.Find(id);
        ViewBag.TestMovie = movie;
        return View();
}


Nothing wrong with a late bound object getting pushed to the View. However, ASP.NET MVC also gives us the option to pass a strongly typed object over to a View, which will give us a safer and more intellisense friendly way to work with Models. The equivalent of the above using strongly typed objects would be:



public ActionResult Details(int? id)
{
    Movie movie = db.Movies.Find(id);
    return View(movie);
}


It's even less code now. You can pass model entries directly into the Views and you can specify in the View just what kind of object it should be expecting. The Details View for example, would specify the following at the top of the page.



@model WebApplication1.Models.Movie

<p>
  @Html.DisplayFor(model => model.Title)
</p>

<p>
  @Html.DisplayFor(model => model.ReleaseDate)
</p>


You can also pass a list of Movie objects to the View. To do so:



private MovieDBContext db = new MovieDBContext();

public ActionResult Index()
{
    return View(db.Movies.ToList());
}


Well that was easy enough. Your View would then need the following @model directive:



@model IEnumerable<WebApplication1.Models.Movie>

@foreach (var item in Model) {
    <p>
            @Html.DisplayFor(modelItem => item.Title)
    </p>
    
    <p>
        @Html.DisplayFor(modelItem => item.ReleaseDate)
    </p>
}


You can use the strongly typed Model object to grab your collection of entries.

I guess there will be a part 3 to this write up as it seems to have run a bit long and I don't want to bore anyone. This should be enough however to get a beginner started on integrating the Entity Frameworks scaffolding features onto their projects and hopefully give enough of an idea on how everything works so that one can build it up from scratch. In part 3, I'll cover DataAnnotations and how to Post data back to a View.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment