Hello All, We are going to start new batch from next week. message/call or mail us for more details.

20 February 2014

MVC Introduction - DotNet Brother

Introduction

ASP.NET MVC is a Web development framework from Microsoft that combines the effectiveness and
tidiness of model-view-controller (MVC) architecture. It is the architectural pattern based on ASP.NET framework which provides a clean and elegant way of developing Web application.

Limitation of ASP.Net Web Forms

Traditional ASP.NET Web Forms development was great in principle, but reality proved more
complicated. Let us discuss some limitation of web forms which are seen as drawbacks:-

View State weight: The actual mechanism for maintaining state across requests (known as View State) results in large blocks of data being transferred between the client and server. This data can reach hundreds of kilobytes in even modest Web applications, and it goes back and forth with every request, leading to slower response times and increasing the bandwidth demands of the server.

Page life cycle: The mechanism for connecting client-side events with server-side event handler code, part of the page life cycle, can be extraordinarily complicated and delicate. Few developers have success manipulating the control hierarchy at runtime without getting View State errors or finding that some event handlers mysteriously fail to execute.

Url: In ASP.NET web forms the request URL points to physical files and the structure of the URL is not SEO friendly. Also, now is the time when URL structure is very important and clean URLs and control over URLs is very much desired.

Code Behind: Code behind model, in my opinion, is the best part of ASP.NET. It provides clear separation of concern. From a developers perspective having the code behind file provides a great way to write the server side logic without having to write code between the HTML markups.

Key Benefits of ASP.net MVC

MVC Architecture

There are three pieces to the MVC architecture:-

The model—The domain that your software is built around. If you were building a blog, your models might be post and comment. In some contexts, the term model might refer to a view-specific model—a representation of the domain for the specific purpose of being displayed in the user interface.

 The view—The visual representation of a model, given some context. It’s usually the resulting markup that the framework renders to the browser, such as the HTML representing the blog post.

 The controller—The coordinator that provides the link between the view and the model. The controller is responsible for processing input, acting upon the model, and deciding on what action should be performed, such as rendering a view or redirecting to another page.

Tight Control over HTML and HTTP

ASP.NET MVC–generated pages don’t contain any View State data, so they can be hundreds of kilobytes smaller than typical pages from ASP.NET Web Forms. Despite today’s fast broadband connections, this economy of bandwidth still gives an enormously improved end-user experience.
Like Ruby on Rails, ASP.NET MVC works in tune with HTTP. You have total control over the requests passing between the browser and server, so you can fine-tune your user experience as much as you like.

Extensibility

The ASP.NET MVC designers set out to give you three options for each MVC Framework component:

  • Use the default implementation of the component as it stands (which should be enough for most applications).
  • Derive a subclass of the default implementation to tweak its behavior.
  • Replace the component entirely with a new implementation of the interface or abstract base class.
Testability
The MVC architecture gives you a great start in making your application maintainable and testable because you naturally separate different application concerns into different, independent software pieces. You can write test scripts that simulate user interactions without needing to guess which HTML element structures, CSS classes, or IDs the framework will generate, and you do not have to worry about the structure changing unexpectedly.

Simple Registration Page Using Asp.Net MVC 4 - DotNet Brother

Follow the step :

Lets first open your Visual studio 2012 and create an empty asp.net mvc 4 application with razor engine then Add a controller to the project named ”HomeController.cs” with below code:

using SimpleDataEntryApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SimpleDataEntryApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            int hour = DateTime.Now.Hour;
            ViewBag.Time = hour < 12 ? "Good Morning!" : "Good Afternoon!";
            return View();
        }
    }
}


Now  create a model class and named “Seminar.cs” and add some properties like below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SimpleDataEntryApp.Models
{
    public class Seminar
    {
        public string name { getset; }
        public string email { getset; }
        public string phone { getset; }
        public bool? willAttend { getset; }
    }
}
Now add a view to the project by right clicking in the Index() ActionResult in the “HomeController.cs” file and named it “Index.cshtml”.
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
       <h3> @ViewBag.Time </h3><br />
        Simple Registration Page Using Asp.Net MVC 4<br />
        Click here to insert records &nbsp;@Html.ActionLink("here","RegForm")
    </div>
</body>
</html>
Now you  have added an ActionLink in this view to move to the next page when we click on “here”.
Next you have to add  a ViewResult method in the “HomeController.cs” file like below:


[HttpGet]
public ViewResult RegForm()
{
   return View();
}
now also add a view to this viewresult and named it as ”RegForm” and make it a strongly-typed view like this:

Now lets write few code in the “RegForm.cshtml” file.

@model SimpleDataEntryApp.Models.Seminar
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>RegForm</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        <p>Name : @Html.TextBoxFor(m => m.name)</p>
        <p>Email : @Html.TextBoxFor(m => m.email)</p>
        <p>Phone : @Html.TextBoxFor(m => m.phone)</p>
        <p>
            Will you attend? : @Html.DropDownListFor(m => m.willAttend, new[]{
                             new SelectListItem() {Text = "Yes", Value = bool.TrueString},
                             new SelectListItem() {Text= "No", Value= bool.FalseString},
                         },"Choose an option")
        </p>
        <input type="submit" value="Submit" />
    }
</body>
</html>


so in this view, we have created a simple form with three textboxes and a dropdownlist and a submit button to submit the values.
Now we have created a form, next we need a page to display the values which user has inputted in the form, so add another viewresult to the controller that is “HomeController.cs” like this:


[HttpPost]
public ViewResult RegForm(Seminar seminarResponse)
{
   return View("Thanks", seminarResponse);
}
So the whole “HomeController.cs” file look like this:
using SimpleDataEntryApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SimpleDataEntryApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            int hour = DateTime.Now.Hour;
            ViewBag.Time = hour < 12 ? "Good Morning!" : "Good Afternoon!";
            return View();
        }
        [HttpGet]
        public ViewResult RegForm()
        {
            return View();
        }
        [HttpPost]
        public ViewResult RegForm(Seminar seminarResponse)
        {
            return View("Thanks", seminarResponse);
        }
    }
}


Now add a view to the viewresult RegForm(Seminar seminarResponse) by right clicking to it named “Thanks.cshtml” and make it a strongly-typed view like this:
 
Now write the below code in it:
@model SimpleDataEntryApp.Models.Seminar
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Thanks</title>
</head>
<body>
    <div>
        <h1>Thank you, @Model.name</h1>
        @if (Model.willAttend == true)
        {
            @: OK
        }
        else
        {
            @:Sorry:(
        }
    </div>
</body>
</html>


Output
Now run the application:




















When you click on “here” will open the “RegForm.cshtml”


Fill the form with appropriate values and click on submit button: