ASP.NET MVC Model Example

This article describes you about what is ASP.NET Model, example of how to use and bind model data, how to make GET or Post request using model.


ASP.NET MVC Model

With ASP.NET MVC Model you can hold and manipulate data. It contains all application logic like business rules, validation or data access logic. It is used for retrieve from database and store data to database.


Follow below steps to understand how to use and bind model data.


Create ASP.NET MVC application

Create a simple ASP.NET MVC application using Visual Studio. Follow Getting started Tutorial with ASP.NET MVC to create your basic application. It helps you to create basic MVC application, use controller, action method and ActionResult.


Add MVC Model

Open application created in previous step. Add folder with name Models.

Right click on Models folder -> Select Add -> Select Class.

Name the class file Customer.cs and click Ok.

Open the Customer model to add its attribute. You add properties of particular entity in model. Like in Customer model you will add properties like CustomerID, Name, City etc. You can control the behavior or each property by adding DataAnnotations validation to it.

See details about how to validate ASP.NET MVC model using DataAnnotation attribute?

Add below properties to Customer.cs model.


namespace FirstMVC.Models
{
    public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string City { get; set; }             
    }
}
            

Use Model in Controller

In this step you will use Customer model in Controller. Use the properties of Customer to set values and send Customer model to view for display. Check for more details on MVC Controller, Action method and ActionResult.

You will write two different method to deal Customer model. One for GET request and another for POST request. For GET you will read values from Database and display it in View and when you make any changes on View you need to use POST method to update database.

Open HomeController and add below code which sets value to Customer model and return to View.


public ActionResult CustomerDetails()
{
    Customer cust = new Customer();
    cust.CustomerID = "ALFKI";
    cust.CompanyName = "Alfreds Futterkiste";
    cust.ContactName = "Maria Anders";
    cust.ContactTitle = "Sales Representative";
    cust.City = "Berlin";

    return View(cust); 
}            
            

Display Model data in View

Now you will add CustomerDetails view.

From HomeController right click on CustomerDetails Action method and select Add View. From Add View window do not change any settings and click OK.

This will add CustomerDetails.cshtml file in Views -> Home folder. Open this file and add below HTML code.


<html>
<head>
    <title>Customer Details - dotnetmentors.com</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" 
            href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/
                css/bootstrap.min.css" />
</head>
<body>
    @model FirstMVC.Models.Customer
    <div class="container">
        <h2>
            <a href="http://dotnetmentors.com">
                <img src="http://dotnetmentors.com/images/dotnetmentors.png" 
                alt="dotnetmentors.com" /></a>
            Customer Details
        </h2>
        @using (Html.BeginForm("CustomerDetails", "home"))
        {            
            <div class="form-group">
                <table>
                    <tr>
                        <td>
                            @Html.Label("Customer ID:")
                        </td>
                        <td>
                            @Html.TextBoxFor(m => m.CustomerID)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.Label("Company Name:")
                        </td>
                        <td>
                            @Html.TextBoxFor(m => m.CompanyName)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.Label("Contact Name:")
                        </td>
                        <td>
                            @Html.TextBoxFor(m => m.ContactName)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.Label("Contact Title:")
                        </td>
                        <td>
                            @Html.TextBoxFor(m => m.ContactTitle)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.Label("City:")
                        </td>
                        <td>
                            @Html.TextBoxFor(m => m.City)
                        </td>
                    </tr>
                    <tr>
                        <td>
                             
                        </td>
                        <td>
                            <button type="submit" class="btn btn-default">
                                Submit</button>
                        </td>
                    </tr>
                </table>
            </div>
            
        }
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/
                    jquery/1.11.1/jquery.min.js"  type="text/javascript"></script>
    <script src="http://maxcdn.bootstrapcdn.com/
                        bootstrap/3.2.0/js/bootstrap.min.js"    type="text/javascript"></script>
</body>
</html>
 
    
    

Execute the application and browse to http://localhost:52937/home/CustomerDetails. You will see the model data is binded to view and display as below output.

ASP.NET MVC Model example - dotnetmentors.com


Post request with ASP.NET MVC Model

In this step you will write code to handle POST request. When user clicks on button it should execute POST method to make Insert / Update / Delete operation.

UrlRoutingModule of MVC will route the request to appropriate POST method. See how ASP.NET MVC Request flow?

Open HomeController.cs file and add implementation of CustomerDetails Action method POST request.


[HttpPost]
public ActionResult CustomerDetails(Customer cust)
{
            
    //code to update Customer details in database
    return View();
}
    
            

Put a break point on above code and execute your application. Browse to http://localhost:52937/home/CustomerDetails. Update some data from Textboxes on screen and click submit.

When breakpoint gets hit check the values of Customer model which is pass to Action method as input parameter.

I changed the values of Customer Model's City and ContactTitle fields to Pune and Manager respectively and click Submit. I got those updated values in Action method.

You can use those updated values to make database operation.

ASP.NET MVC POST Action method - dotnetmentors.com


Download source code

Speak your mind :
Leave a comment for this article on dotnetbloogers.com