Friday, February 24, 2012

MVC

Model View Controller Architecture

MVC is one of the architectural pattern used in software engineering.MVC architecture used to separate user interface from application logic so it allow user to write codes clearly. By using MVC architecture developer can made more maintainable applications.MVC architecture separate the application logic, UI logic and business logic from each other.

Model: Data and the business rules of the application are hold by the model. It doesn’t need to know how this data present to the user it only represent data of an application.
View: Decide how the data present to the user. Not depend on the application logic.
Controller: act as a bridge between model and view. User requests are go through the controller to the model.



Sample MVC Project
Here I’m going to develop a very simple web application using MVC3.To create a new MVC3 application, follow these steps,

File à new àProjectàASP.Net MVC3 web application

You can create project with sample template or without them (empty).If you select empty template you’ll have a file structure as following.


·         Create a new folder inside view and give a proper name to it. (I’ll name it as “Test”).
·         Creating the view: - right click on the Test folder and select AddView
Then give a proper name and click on Add button.(as the view engine I’ll use Razor)

·         Creating the controller: - right click on the controller folder and select AddController
Then give a proper name and click on Add button. (it is better to give the name of your view folder as controller name. As I name it as ‘TestController’ )

·         Creating the Model: - right click on the Model folder and select AddClass
Then give a proper name and click on Add button. (I’ll name it as “TestModel”).

·         For the database connection purpose I have add a new folder called data and added an entity data model to it.

Model class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcApplication2.Data;

namespace MvcApplication2.Models
{
    /// <summary>
    /// Model class
    /// </summary>
    public class TestModel
    {
        /// <summary>
        /// Gets all users.
        /// </summary>
        /// <returns></returns>
        public static IList<User> GetAllUsers()
        {
            NORTHWINDEntities northwindEntities = new NORTHWINDEntities();
            IList<UserData> udList = (from u in northwindEntities.UserDatas
                                      select u).ToList();
            IList<User> users = new List<User>();
            foreach (var item in udList)
            {
                users.Add(new User() {NID=item.NID,FirstName=item.FirstName,LastName=item.LastName,Age=item.Age });
            }
            return users;
                
        }

    }

    /// <summary>
    /// class for define entity properties
    /// </summary>
    public class User
    {
        /// <summary>
        /// Gets or sets the NID.
        /// </summary>
        /// <value>
        /// The NID.
        /// </value>
        public string NID { get; set; }
        /// <summary>
        /// Gets or sets the first name.
        /// </summary>
        /// <value>
        /// The first name.
        /// </value>
        public string FirstName { get; set; }
        /// <summary>
        /// Gets or sets the last name.
        /// </summary>
        /// <value>
        /// The last name.
        /// </value>
        public string LastName { get; set; }
        /// <summary>
        /// Gets or sets the age.
        /// </summary>
        /// <value>
        /// The age.
        /// </value>
        public int Age { get; set; }
    }
}


View
@{
    ViewBag.Title = "TestView";
}
<script type="text/javascript">
    function GetAllUsers() {
        $.ajax({
            async: false,
            type: 'Get',
            url: '/Test/GetAllUsers',
            success: function (result) {
                $("#UserTable").attr("style", "visibility:visible");
                var content = [];
                for (var i = 0; i < result.length; i++) {
                    content.push("<tr><td>" + result[i].NID + "</td><td>" + result[i].FirstName + "</td><td>" + result[i].LastName + "</td><td>" + result[i].Age + "</td></tr>");
                }
                jQuery("#UserTable").find('tbody').html(content.join(""));

            },
            error: function (e) {
                alert(e);
            }


        });

    }

    function ClearGrid() {
        jQuery("#UserTable").find('tbody').html("");
        $("#UserTable").attr("style", "visibility:hidden");
    }


</script>
<h2>
    TestView</h2>
<html>
<body>
<button onclick="GetAllUsers();">Get All Users</button>
<button onclick="ClearGrid();">Clear Grid</button>
    <table id="UserTable" border="1" style="visibility:hidden">
        <thead>
            <tr>
                <th>
                    NID
                </th>
                <th>
                    First Name
                </th>
                <th>
                    Last Name
                </th>
                <th>
                    Age
                </th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</body>
</html>



Controller Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    /// <summary>
    /// Controller class
    /// </summary>
    public class TestController : Controller
    {
        //
        // GET: /Test/

        /// <summary>
        ///controller method for testview
        /// </summary>
        /// <returns></returns>
        public ActionResult TestView()
        {
            return View();
        }

        /// <summary>
        /// Gets all users.
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public virtual JsonResult GetAllUsers()
        {
            IList<User> users=TestModel.GetAllUsers();
            return Json(users, JsonRequestBehavior.AllowGet);
        }

    }
}



No comments:

Post a Comment