Friday, December 28, 2012

Introduction to MVC


Introduction to MVC

ASP.NET MVC is a new web application framework from Microsoft.MVC stands for Model-View-Controller, a pattern that’s becoming increasingly popular with web development frameworks. ASP.NET MVC is an alternative and a complement to Web Forms, which means you won’t be dealing with pages and controls, postbacks or view state, or complicated asp.net event life cycles.
Basically, MVC is a framework methodology that divides an application's implementation into three component roles: models, views, and controllers. Hence in Asp.net MVC you need to play with controllers, actions, and views.

MVC Pattern

The Model-View-Controller (MVC) pattern is an adaptation of a pattern generated from the Smalltalk community in the 1970s by Trygve Reenskaug. It was popularized for use on the web with the advent of Ruby on Rails in 2003.
  1. Model

    Models in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database for example: we might have a Product class that is used to represent order data from the Products table inside SQL.
  2. View

    Views in a MVC based application are the components responsible for displaying the application's user interface. Typically this UI is created off of the model data for example:
  3. Controller

    Controllers in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information - it is the controller that handles and responds to user input and interaction.

MVC Web Application Advantages

The ASP.NET MVC Framework is a new framework and have the following advantages over Web Forms approach (means over ASP.Net):
  1. Separation of concern

    In MVC the application is divided to Model, View and Controller parts which make it easier to manage the application complexity.
  2. TDD

    The MVC framework brings better support to test-driven development.
  3. Extensible and pluggable

    MVC framework components were designed to be pluggable and extensible and therefore can be replaced or customized easier then Web Forms.
  4. Full control over application behavior

    MVC framework doesn’t use View State or server based forms like Web Forms. This gives the application developer more control over the behaviors of the application and also reduces the bandwidth of requests to the server.
  5. ASP.NET features are supported

    MVC framework is built on top of ASP.NET and therefore can use most of the features that ASP.NET include such as the providers architecture, authentication and authorization scenarios, membership and roles, caching, session and more.
  6. URL routing mechanism

    MVC framework supports a powerful URL routing mechanism that helps to build a more comprehensible and searchable URLs in your application. This mechanism helps to the application to be more addressable from the eyes of search engines and clients and can help in search engine optimization.
The ASP.NET MVC simplifies the complex parts of ASP.net Web Forms without any compromise of the power and flexibility of ASP.NET platform. ASP.net MVC implements Model-View-Controller UI pattern for web application development that lets you allows to develop applications in a loosely couples manner. MVC pattern is separating the application in three parts- Model, View and Controller.

Setting default submit button in MVC3 razor using jQuery

In Asp.net MVC, sometimes we required to post the form on Enter key press. Asp.net MVC has no default button property like Asp.net. However, we can achieve this functionality by using jQuery in MVC.

Set Form DefaultButton Property using jQuery

  1. <script type="text/javascript"> $(document).ready(function (){ $("#MyForm").keypress(function (e) { kCode = e.keyCode || e.charCode //for cross browser
  2. if (kCode == 13) { var defaultbtn = $(this).attr("DefaultButton");
  3. $("#" + defaultbtn).click();
  4. return false;
  5. }
  6. });
  7. });
  8. </script>
  9. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { DefaultButton = "SubmitButton", id = "MyForm" }))
  10. {
  11. @Html.TextBox("txtname")
  12. <span>Please Enter value and then press Enter Key</span><br />
  13. <input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />
  14. }
Summary
In this article I try to explain the default submit behavior of form in MVC. I hope you will refer this article for your need. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

ViewData vs ViewBag vs TempData objects in mvc3 razor

In Asp.net MVC 3, we have three objects - ViewData, ViewBag and TempData to pass data from controller to view and in next request. Now question is that when to use ViewData, VieBag and TempData. All these three objects have its own importance. In this article I am trying to expose the use of these three.

ViewData

  1. ViewData is a dictionary object that is derived from ViewDataDictionary class.
  2. ViewData is used to pass data from controller to corresponding view.
  3. It’s life lies only during the current request.
  4. If redirection occurs then it’s value becomes null.
  5. It’s required typecasting for complex data type and check for null values to avoid error.

ViewBag

  1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  2. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
  3. It’s life also lies only during the current request.
  4. If redirection occurs then it’s value becomes null.
  5. It doesn’t required typecasting for complex data type.

TempData

  1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
  2. TempData is used to pass data from current request to subsequent request means incase of redirection.
  3. It’s life is very short and lies only till the target view is fully loaded.
  4. It’s required typecasting for complex data type and check for null values to avoid error.
  5. It is used to store only one time messages like error messages, validation messages.

ViewData, ViewBag and TempData Current Request Example

  1. public class HomeController : Controller
  2. {
  3. public ActionResult Index()
  4. {
  5. var emp = new Employee
  6. {
  7. EmpID=101,
  8. Name = "Deepak",
  9. Salary = 35000,
  10. Address = "Delhi"
  11. };
  12. ViewData["emp"] = emp;
  13. ViewBag.Employee = emp;
  14. TempData["emp"] = emp;
  15. return View(); }
  16. }
  1. @model MyProject.Models.EmpModel;
  2. @{
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. ViewBag.Title = "Welcome to Home Page";
  5. var viewDataEmployee = ViewData["emp"] as Employee; //need typcasting
  6. var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
  7. }
  8. <h2>Welcome to Home Page</h2>
  9. <div>
  10. <a href="/Employees">
  11. <img src='@Url.Content("\\Content\\Images\\101.jpg")' alt="Best Employee "/>
  12. </a>
  13. <div>
  14. This Year Best Employee is!
  15. <h4>@ViewBag.emp.Name</h4>
  16. <h3>@viewDataEmployee.Name</h3>
  17. <h2>@tempDataEmployee.Name</h2>
  18. </div>

ViewData, ViewBag and TempData Next Request Example

  1. public ActionResult About()
  2. {
  3. var emp = new Employee {
  4. EmpID=101,
  5. Name = "Deepak",
  6. Salary = 35000,
  7. Address = "Delhi"
  8. };
  9. ViewData["emp"] = emp;
  10. ViewBag.Employee = emp;
  11. TempData["emp"] = emp;
  12. //After the redirection, ViewData and ViewBag objects will be null
  13. //Only TempData will exist after redirection
  14. return new RedirectResult(@"~\About\");
  15. }
  1. @model MyProject.Models.EmpModel;
  2. @{
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. ViewBag.Title = "About";
  5. var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
  6. }

TempData with Keep method

If you want to keep value in TempData object after request completion, you need to call Keep method with in the current action. There are two overloaded Keep methods to retains value after current request completion.
  1. void Keep()

    Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.
    1. @model MyProject.Models.EmpModel;
    2. @{
    3. Layout = "~/Views/Shared/_Layout.cshtml";
    4. ViewBag.Title = "About";
    5. var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
    6. TempData.Keep(); // retains all strings values
    7. }
  2. void Keep(string key)

    Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.
    1. @model MyProject.Models.EmpModel;
    2. @{
    3. Layout = "~/Views/Shared/_Layout.cshtml";
    4. ViewBag.Title = "About";
    5. var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
    6. TempData.Keep("emp"); // retains only "emp" string values
    7. }

Key point about TempData and TempData.Keep()

  1. Items in TempData will only tagged for deletion after they have read.
  2. Items in TempData can be untagged by calling TempData.Keep(key).
  3. RedirectResult and RedirectToRouteResult always calls TempData.Keep() to retain items in TempData.
Summary
In this article I try to explain the difference between ViewData, ViewBag and TempData. I hope you will refer this article for your need. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

How to use ViewModel in mvc3

In asp.net mvc, a controller can pass single object to the corresponding view. This object may be a simple object or a complex object. ViewModel is a complex object that may contain multiple entities or objects from different data models or data source. Basically ViewModel is a class that specify data model used in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Key Points about View Model

  1. ViewModel contain fields that are represented in the view (for LabelFor,EditorFor,DisplayFor helpers)
  2. ViewModel can have specific validation rules using data annotations or IDataErrorInfo.
  3. ViewModel can have multiple entities or objects from different data models or data source.

ViewModel Example

Designing the model

  1. public class UserLoginModel
  2. {
  3. [Required(ErrorMessage = "Please enter your username")]
  4. [Display(Name = "User Name")]
  5. [MaxLength(50)]
  6. public string UserName { get; set; }
  7. [Required(ErrorMessage = "Please enter your password")]
  8. [Display(Name = "Password")]
  9. [MaxLength(50)]
  10. public string Password { get; set; }
  11. }

Presenting the model in the view

  1. @model MyModels.UserLoginModel
  2. @{
  3. ViewBag.Title = "User Login";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. @using (Html.BeginForm())
  7. {
  8. <div class="editor-label">
  9. @Html.LabelFor(m => m.UserName)
  10. </div>
  11. <div class="editor-field">
  12. @Html.TextBoxFor(m => m.UserName)
  13. @Html.ValidationMessageFor(m => m.UserName)
  14. </div>
  15. <div class="editor-label">
  16. @Html.LabelFor(m => m.Password)
  17. </div>
  18. <div class="editor-field">
  19. @Html.PasswordFor(m => m.Password)
  20. @Html.ValidationMessageFor(m => m.Password)
  21. </div>
  22. <p>
  23. <input type="submit" value="Log In" />
  24. </p>
  25. </div>
  26. }

Working with Action

  1. public ActionResult Login()
  2. {
  3. return View();
  4. }
  5. [HttpPost]
  6. public ActionResult Login(UserLoginModel user)
  7. {
  8. // To acces data using LINQ
  9. DataClassesDataContext mobjentity = new DataClassesDataContext();
  10. if (ModelState.IsValid)
  11. {
  12. try
  13. {
  14. var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
  15. if (q.Count > 0)
  16. {
  17. return RedirectToAction("MyAccount");
  18. }
  19. else
  20. {
  21. ModelState.AddModelError("", "The user name or password provided is incorrect.");
  22. }
  23. }
  24. catch (Exception ex)
  25. {
  26. }
  27. }
  28. return View(user);
  29. }

Some Tips for using ViewModel

  1. In ViewModel put only those fields/data that you want to display on the view/page.
  2. Since view reperesents the properties of the ViewModel, hence it is easy for rendering and maintenance.
  3. Use a mapper when ViewModel become more complex.
In this way, ViewModel help us to organize and manage data in a strongly-typed view with more flexible way than complex objects like models or ViewBag/ViewData objects.
Summary
In this article I try to expose the ViewModel with example. I hope you will refer this article for your need. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

MVC Data Annotations for Model Validation

Data validation is a key aspect for developing web application. In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework orm models.
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.

Data Annotation Validator Attributes

  1. DataType

    Specify the datatype of a property
  2. DisplayName

    specify the display name for a property.
  3. DisplayFormat

    specify the display format for a property like different format for Date proerty.
  4. Required

    Specify a property as required.
  5. ReqularExpression

    validate the value of a property by specified regular expression pattern.
  6. Range

    validate the value of a property with in a specified range of values.
  7. StringLength

    specify min and max length for a string property.
  8. MaxLength

    specify max length for a string property.
  9. Bind

    specify fields to include or exclude when adding parameter or form values to model properties.
  10. ScaffoldColumn

    specify fields for hiding from editor forms.

Designing the model with Data Annotations

  1. using System.ComponentModel;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Web.Mvc;
  4. namespace Employee.Models
  5. {
  6. [Bind(Exclude = "AlbumId")]
  7. public class Employee
  8. {
  9. [ScaffoldColumn(false)]
  10. public int EmpId { get; set; }
  11. [DisplayName("Employee Name")]
  12. [Required(ErrorMessage = "Employee Name is required")]
  13. [StringLength(100,MinimumLength=3)]
  14. public String EmpName { get; set; }
  15. [Required(ErrorMessage = "Employee Address is required")] [StringLength(300)]
  16. public string Address { get; set; }
  17. [Required(ErrorMessage = "Salary is required")] [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
  18. public int Salary{ get; set; }
  19. [Required(ErrorMessage = "Please enter your email address")] [DataType(DataType.EmailAddress)]
  20. [Display(Name = "Email address")]
  21. [MaxLength(50)]
  22. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
  23. public string Email { get; set; }
  24. }
  25. }
Once we have define validation to the model by using data annotations, these are automatically used by Html Helpers in views. For client side validation to work, please ensure that below two <SCRIPT> tag references are in the view.
  1. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  2. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

Presenting the model in the view

  1. @model Employee.Models
  2. @{
  3. ViewBag.Title = "Employee Details";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. @using (Html.BeginForm())
  7. {
  8. <div class="editor-label">
  9. @Html.LabelFor(m => m.EmpName)
  10. </div>
  11. <div class="editor-field"> @Html.TextBoxFor(m => m.EmpName) @Html.ValidationMessageFor(m => m.EmpName)
  12. </div>
  13. <div class="editor-label"> @Html.LabelFor(m => m.Address)
  14. </div>
  15. <div class="editor-field"> @Html.TextBoxFor(m => m.Address) @Html.ValidationMessageFor(m => m.Address)
  16. </div>
  17. <div class="editor-label"> @Html.LabelFor(m => m.Salary)
  18. </div>
  19. <div class="editor-field"> @Html.TextBoxFor(m => m.Salary) @Html.ValidationMessageFor(m => m.Salary)
  20. </div>
  21. <div class="editor-label">
  22. @Html.LabelFor(m => m.Email)
  23. </div>
  24. <div class="editor-field"> @Html.TextBoxFor(m => m.Email) @Html.ValidationMessageFor(m => m.Email)
  25. </div>
  26. <p> <input type="submit" value="Save" />
  27. </p>
  28. </div>
  29. }
Summary
In this article I try to expose the Data Annotations with example. I hope you will refer this article for your need. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Partial View in Asp.net MVC3 Razor

A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views.
We can use partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar etc.

Creating A Partial View

A partial view has same file extension(.cshtml) as regular view. To create a partial view do right click on shared folder (\Views\Shared) in solution explorer and click on "Add New View" option and then give the name for partial view and also checked the Create a partial view option as shown in fig.
 

Note

  1. It is best practice to create partial view in the shared folder and partial view name is preceded by "_", but it is not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.

Rendering Partial View

A partial view is rendered by using the ViewUserControl class that is inherited/derived from the ASP.NET UserControl class. The Partial, RenderPartial, RenderAction helper methods are used to render partial view in mvc3 razor.
  1. <div> @Html.Partial("_Comments") </div>
  2. <div> @{Html.RenderPartial("_Comments");} </div>
The main difference between above two methods is that the Partial helper method renders a partial view into a string while RenderPartial method writes directly into the response stream instead of returning a string.
  1. <div> @{Html.RenderAction("_Category","Home");} </div>

Note

  1. Partial or RenderPartial methods are used when a model for the page is already populated with all the information. For example in a blog to show an article comment we would like to use Partial or RenderPartial methods since an article information are already populated in the model.
  2. RenderAction method is used when some information is need to show on multiple pages. Hence partial view should have its own model. For example to category list of articles on each and every page we would like to use RenderAction method since the list of category is populated by different model.

Render Partial View Using jQuery

Sometimes we need to load a partial view with in a popup on run time like as login box, then we can use jQuery to make an AJAX request and render a Partial View into the popup. In order to load a partial view with in a div we need to do like as:
  1. <script type="text/jscript">
  2. $('#divpopup').load('/shared/_ProductCategory’);
  3. </script>
Summary
I hope you will enjoy this tips and tricks while programming with Asp.Net MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Inline CSS and Styles with Html Helpers in MVC3 Razor

In Asp.net, we can custom the look and feel of a server controls by using CSS class,id and inline css. Similarly, we can change the style of Html Helpers in MVC razor. I this article, I am going to explain how can change the style of a Html Helpers by using CSS.

CSS Class

  1. .inputclass
  2. {
  3. width:100px;
  4. height:25px;
  5. }

Apply CSS Class to Html Helpers

Suppose above css class is defined in the external style sheet. Now you want to apply this class to html helpers then we need to add class name by using @class like as :
  1. @Html.TextBox("Name", new { @class="inputclass" })
  2. @Html.TextBoxFor(model => model.Name, new { @class="inputclass" })

Apply Inline CSS to Html Helpers

We can also add inline css to html helpers by using style like as :
  1. @Html.TextBoxFor(model => model.Name, new { style="width:100px;height:25px" })
  2. @Html.TextBox("Name", new { style="width:100px;height:25px" })

Enable jQuery Intellisense support to MVC3 Razor

jQuery intellisense support helps a lot while programming with jQuery. By default Visual Studio doesn't provide us the jQuery intellisense support. We can enable the jQuery intellisense support in Visual Studio with MVC Razor by adding vsdoc.js file to your view like as :
  1. @if (false)
  2. {
  3. <script src="~/Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script>
  4. }
The above if-statement prevents the rendering of script tag into the html source code and it used only by the Visual Studio for jQuery intellisense support. To check jQuery intellisense type the $ or $( between your $(document).ready(function() function and you can see the intellisense as shown in fig.
 

Note

  1. In MVC Razor, there is no central place to add the reference to the vsdoc.js file. We need to add this code line to each every view separately to enable the IntelliSense support for jQuery.

Understading Controllers and Actions in MVC Razor

Asp.net MVC Controllers are responsible for controlling the flow of the application execution. When you make a request (means request a page) to MVC applications , a controller is responsible for returning the response to that request. A controller can have one or more actions. A controller action can return different types of action results to a particular request.

Controller

Basically, the controller Receives input like as form values, query strings values etc. from users via the View and perform required operations on the user's inputs with the help of Model and passing the results back to the View. Actually, controllers are classes that have methods or action results and these actions results are called by the routing system to process a particular request.

Creating a Controller

For creating a controller, do right-click on the Controller folder in your mvc application and select the menu option Add, Controller. After selection the Add Controller dialog is being displayed as shown in fig. Now enter your controller name before Controller word.
 
In this way you have successfully created your controller as shown in fig.

Controller Actions and Helper Methods

Controller actions are methods defined in the controller class and responsible to perform required operations on the user's inputs like as form values, query strings values etc. with the help of Model and passing the results back to the View. Asp.net MVC has the following Built-in ActionResults Type and Helper methods :
  1. ViewResult

    Returns a ViewResult which renders the specified or default view by using controller View() helper method.
  2. PartialViewResult

    Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) by using controller PartialView() helper method.
  3. RedirectResult

    Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL by using controller Redirect() helper method.
  4. RedirectToRouteResult

    Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection to an action method or specific route entry by using controller RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() helper methods.
  5. ContentResult

    Returns a ContentResult which renders raw text like as "Hello, DotNet Tricks!" by using controller Content() helper method.
  6. JsonResult

    Returns a JsonResult which serializes an object in JSON format ( like as "{ "Message": Hello, World! }") and renders it by using controller Json() helper method.
  7. JavaScriptResult

    Returns a JavaScriptResult which renders a snippet of JavaScript code like as "function hello() { alert(Hello, World!); }" by using controller JavaScript() helper method. This is used only in AJAX scenarios.
  8. FileResult

    Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc. by using controller File() helper method.
  9. EmptyResult

    Returns no result returned by an action. This has no controller helper method.
  10. HttpNotFoundResult

    Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by using controller HttpNotFound() helper method.
  11. HttpUnauthorizedResult

    Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code(means "not authorized") response. This has no controller helper method. This is used for authentication (forms authentication or Windows authentication) to ask the user to log in.
  12. HttpStatusCodeResult

    Returns an HttpStatusCodeResult which renders a specified HTTP code response. This has no controller helper method.






No comments:

Post a Comment