Learn MVC Step 2 - Model View Controller

In this article we will learn to create model, controller and finally we will add view to render the list of categories by using list template. First we will try to render the list of hard coded values then in next article we will use Empty Framework to save data into database and show data from database. But for now we need to focus how we can create model, controller and view. so add a new model in models folder with name "Category", right click on the Models folder and click Add => select Class and add following code in it

public class Category
{
    [Key]
    public int CategoryId { get; set; }

    [Required]
    [Display(Name ="Category Name")]
    [StringLength(30, ErrorMessage="The {0} must be between {2} to {1} characters", MinimumLength = 5)]
    public String CategoryName { get; set; }        
}
  • Key: Primary key of the table when we will use EF
  • Rebuild: this field is required
  • DisplayName: Label of the property
  • StringLength: String length validation
    • 30: Maximum length
    • 5: Minimum length
    • ErrorMessage: 0: Label of property (in our case "Category Name"), 1: Maximum length and 2: Minimum length digit
    • So the error message will be "The Category Name must be between 5 to 30 characters"

Right click on Controllers folder and - Select Add - Select Controller... - Select MVC 5 Controller - Empty - Click Add - Give the name of the controller "CategoryController" - Click Add

It will add a blank controller to the project, latter we will use the wizard. here is the code

public class CategoryController : Controller
{
    // GET: Category
    public ActionResult Index()
    {
        return View();
    }
}

Say we need to return the list of categories, for time being we will use hard coded values. So add some values to return

public ActionResult Index()
{
    var categories = new List<Category>();
    categories.Add(new Category { CategoryId = 1, CategoryName = "Laptop" });
    categories.Add(new Category { CategoryId = 1, CategoryName = "Software" });
    categories.Add(new Category { CategoryId = 1, CategoryName = "Accessories" });

    return View(categories);
}

Here we added three categories, Laptop, Software and Accessories to the categories list and return this list as View parameter. Rebuild the application because we will use our Category model to render this view. Now add new view

  • Right click inside Index action
  • Select "Add View"
  • Template: select List
  • Model class: select Category (Advance.Learning.WebApp.Models)
  • Data context class: Leave it blank for now, we will use it latter when we will use Entity Framework
  • Click Add

First run the application and navigate to the URL http://localhost:30296/category or http://localhost:30296/category/index

When we access a controller by default it is looking for Index so no need to provide the page name. We can see the page like this:

alt text

It has added every thing we need, link for create new category, edit, update and delete. All these features will not work for now because we have not created any thing for it but we will do it soon.

Let's see what it is created for us

  • See Views folder added a new folder Category, which is the first part of the controller name "CategoryController"
  • It have one file Index.cshtml, which is the action name

Now see the Index.cshtml file, here is the complete code

@model IEnumerable<Advance.Learning.WebApp.Models.Category>
@{
    ViewBag.Title = "Categories";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Categories</h2>    
<p>@Html.ActionLink("Create New", "Create")</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CategoryName)
        </th>
        <th></th>
    </tr>    
    @foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.CategoryId }) |
            @Html.ActionLink("Details", "Details", new { id=item.CategoryId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CategoryId })
        </td>
    </tr>
    }
</table>

There very first line is the type this view expect to be return from the controller to render it which the IEnumerable of our created model Category. Rest are the normal HTML except the @foreach loop, we can call any server side code by using "@" sign. It is used to render the rows of the table.

I change the page title and heading from Index to Categories

@{
    ViewBag.Title = "Categories";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Categories</h2>
  • By using ViewBag.Title we are passing page title value to our Layout page (Master Page)
  • Layout: which layout we are going to use for this page (similar to master page)

So far so good, in our next article we will use Entity Framework Code First model to create our database and use our database to save records and complete all the link on the page like create, edit, detail and delete.




Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • model
  • view
  • controller
By Ali Adravi On 24 Feb, 15  Viewed: 1,458

Other blogs you may like

mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but... By Ali Adravi   On 25 Aug 2013  Viewed: 34,687

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 96,501

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 3,038

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 5,967

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC file upload][1], I promised to post soon about how to upload multiple files. When I was... By Ali Adravi   On 04 Jun 2013  Viewed: 22,233