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.
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.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: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):
Separation of concern
In MVC the application is divided to Model, View and Controller parts which make it easier to manage the application complexity.TDD
The MVC framework brings better support to test-driven development.Extensible and pluggable
MVC framework components were designed to be pluggable and extensible and therefore can be replaced or customized easier then Web Forms.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.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.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
- <script type="text/javascript"> $(document).ready(function (){ $("#MyForm").keypress(function (e) { kCode = e.keyCode || e.charCode //for cross browser
- if (kCode == 13) { var defaultbtn = $(this).attr("DefaultButton");
- $("#" + defaultbtn).click();
- return false;
- }
- });
- });
- </script>
- @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { DefaultButton = "SubmitButton", id = "MyForm" }))
- {
- @Html.TextBox("txtname")
- <span>Please Enter value and then press Enter Key</span><br />
- <input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />
- }
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
- ViewData is a dictionary object that is derived from ViewDataDictionary class.
- ViewData is used to pass data from controller to corresponding view.
- It’s life lies only during the current request.
- If redirection occurs then it’s value becomes null.
- It’s required typecasting for complex data type and check for null values to avoid error.
ViewBag
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
- Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
- It’s life also lies only during the current request.
- If redirection occurs then it’s value becomes null.
- It doesn’t required typecasting for complex data type.
TempData
- TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
- TempData is used to pass data from current request to subsequent request means incase of redirection.
- It’s life is very short and lies only till the target view is fully loaded.
- It’s required typecasting for complex data type and check for null values to avoid error.
- It is used to store only one time messages like error messages, validation messages.
ViewData, ViewBag and TempData Current Request Example
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- var emp = new Employee
- {
- EmpID=101,
- Name = "Deepak",
- Salary = 35000,
- Address = "Delhi"
- };
- ViewData["emp"] = emp;
- ViewBag.Employee = emp;
- TempData["emp"] = emp;
- return View(); }
- }
- @model MyProject.Models.EmpModel;
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- ViewBag.Title = "Welcome to Home Page";
- var viewDataEmployee = ViewData["emp"] as Employee; //need typcasting
- var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
- }
- <h2>Welcome to Home Page</h2>
- <div>
- <a href="/Employees">
- <img src='@Url.Content("\\Content\\Images\\101.jpg")' alt="Best Employee "/>
- </a>
- <div>
- This Year Best Employee is!
- <h4>@ViewBag.emp.Name</h4>
- <h3>@viewDataEmployee.Name</h3>
- <h2>@tempDataEmployee.Name</h2>
- </div>
ViewData, ViewBag and TempData Next Request Example
- public ActionResult About()
- {
- var emp = new Employee {
- EmpID=101,
- Name = "Deepak",
- Salary = 35000,
- Address = "Delhi"
- };
- ViewData["emp"] = emp;
- ViewBag.Employee = emp;
- TempData["emp"] = emp;
- //After the redirection, ViewData and ViewBag objects will be null
- //Only TempData will exist after redirection
- return new RedirectResult(@"~\About\");
- }
- @model MyProject.Models.EmpModel;
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- ViewBag.Title = "About";
- var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
- }
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.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.- @model MyProject.Models.EmpModel;
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- ViewBag.Title = "About";
- var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
- TempData.Keep(); // retains all strings values
- }
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.- @model MyProject.Models.EmpModel;
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- ViewBag.Title = "About";
- var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
- TempData.Keep("emp"); // retains only "emp" string values
- }
Key point about TempData and TempData.Keep()
- Items in TempData will only tagged for deletion after they have read.
- Items in TempData can be untagged by calling TempData.Keep(key).
- 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
- ViewModel contain fields that are represented in the view (for LabelFor,EditorFor,DisplayFor helpers)
- ViewModel can have specific validation rules using data annotations or IDataErrorInfo.
- ViewModel can have multiple entities or objects from different data models or data source.
ViewModel Example
Designing the model
- public class UserLoginModel
- {
- [Required(ErrorMessage = "Please enter your username")]
- [Display(Name = "User Name")]
- [MaxLength(50)]
- public string UserName { get; set; }
- [Required(ErrorMessage = "Please enter your password")]
- [Display(Name = "Password")]
- [MaxLength(50)]
- public string Password { get; set; }
- }
Presenting the model in the view
- @model MyModels.UserLoginModel
- @{
- ViewBag.Title = "User Login";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- @using (Html.BeginForm())
- {
- <div class="editor-label">
- @Html.LabelFor(m => m.UserName)
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(m => m.UserName)
- @Html.ValidationMessageFor(m => m.UserName)
- </div>
- <div class="editor-label">
- @Html.LabelFor(m => m.Password)
- </div>
- <div class="editor-field">
- @Html.PasswordFor(m => m.Password)
- @Html.ValidationMessageFor(m => m.Password)
- </div>
- <p>
- <input type="submit" value="Log In" />
- </p>
- </div>
- }
Working with Action
- public ActionResult Login()
- {
- return View();
- }
- [HttpPost]
- public ActionResult Login(UserLoginModel user)
- {
- // To acces data using LINQ
- DataClassesDataContext mobjentity = new DataClassesDataContext();
- if (ModelState.IsValid)
- {
- try
- {
- var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
- if (q.Count > 0)
- {
- return RedirectToAction("MyAccount");
- }
- else
- {
- ModelState.AddModelError("", "The user name or password provided is incorrect.");
- }
- }
- catch (Exception ex)
- {
- }
- }
- return View(user);
- }
Some Tips for using ViewModel
- In ViewModel put only those fields/data that you want to display on the view/page.
- Since view reperesents the properties of the ViewModel, hence it is easy for rendering and maintenance.
- 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
DataType
Specify the datatype of a propertyDisplayName
specify the display name for a property.DisplayFormat
specify the display format for a property like different format for Date proerty.Required
Specify a property as required.ReqularExpression
validate the value of a property by specified regular expression pattern.Range
validate the value of a property with in a specified range of values.StringLength
specify min and max length for a string property.MaxLength
specify max length for a string property.Bind
specify fields to include or exclude when adding parameter or form values to model properties.ScaffoldColumn
specify fields for hiding from editor forms.
Designing the model with Data Annotations
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Web.Mvc;
- namespace Employee.Models
- {
- [Bind(Exclude = "AlbumId")]
- public class Employee
- {
- [ScaffoldColumn(false)]
- public int EmpId { get; set; }
- [DisplayName("Employee Name")]
- [Required(ErrorMessage = "Employee Name is required")]
- [StringLength(100,MinimumLength=3)]
- public String EmpName { get; set; }
- [Required(ErrorMessage = "Employee Address is required")] [StringLength(300)]
- public string Address { get; set; }
- [Required(ErrorMessage = "Salary is required")] [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
- public int Salary{ get; set; }
- [Required(ErrorMessage = "Please enter your email address")] [DataType(DataType.EmailAddress)]
- [Display(Name = "Email address")]
- [MaxLength(50)]
- [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
- public string Email { get; set; }
- }
- }
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.
- <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
- <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Presenting the model in the view
- @model Employee.Models
- @{
- ViewBag.Title = "Employee Details";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- @using (Html.BeginForm())
- {
- <div class="editor-label">
- @Html.LabelFor(m => m.EmpName)
- </div>
- <div class="editor-field"> @Html.TextBoxFor(m => m.EmpName) @Html.ValidationMessageFor(m => m.EmpName)
- </div>
- <div class="editor-label"> @Html.LabelFor(m => m.Address)
- </div>
- <div class="editor-field"> @Html.TextBoxFor(m => m.Address) @Html.ValidationMessageFor(m => m.Address)
- </div>
- <div class="editor-label"> @Html.LabelFor(m => m.Salary)
- </div>
- <div class="editor-field"> @Html.TextBoxFor(m => m.Salary) @Html.ValidationMessageFor(m => m.Salary)
- </div>
- <div class="editor-label">
- @Html.LabelFor(m => m.Email)
- </div>
- <div class="editor-field"> @Html.TextBoxFor(m => m.Email) @Html.ValidationMessageFor(m => m.Email)
- </div>
- <p> <input type="submit" value="Save" />
- </p>
- </div>
- }
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
- 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.
- <div> @Html.Partial("_Comments") </div>
- <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.
- <div> @{Html.RenderAction("_Category","Home");} </div>
Note
- 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.
- 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:
- <script type="text/jscript">
- $('#divpopup').load('/shared/_ProductCategory’);
- </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
- .inputclass
- {
- width:100px;
- height:25px;
- }
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 :
- @Html.TextBox("Name", new { @class="inputclass" })
- @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 :
- @Html.TextBoxFor(model => model.Name, new { style="width:100px;height:25px" })
- @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 :
- @if (false)
- {
- <script src="~/Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script>
- }
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
- 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 :
ViewResult
Returns a ViewResult which renders the specified or default view by using controller View() helper method.PartialViewResult
Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) by using controller PartialView() helper method.RedirectResult
Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL by using controller Redirect() helper method.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.ContentResult
Returns a ContentResult which renders raw text like as "Hello, DotNet Tricks!" by using controller Content() helper method.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.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.FileResult
Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc. by using controller File() helper method.EmptyResult
Returns no result returned by an action. This has no controller helper method.HttpNotFoundResult
Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by using controller HttpNotFound() helper method.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.HttpStatusCodeResult
Returns an HttpStatusCodeResult which renders a specified HTTP code response. This has no controller helper method.
No comments:
Post a Comment