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.
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.}
ViewData vs ViewBag vs TempData objects in mvc3 razor
we have three objects - ViewData, VieBag 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.
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
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.
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.
@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
}
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.
@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 TemaData and TemaData.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.
When to use ViewModel in mvc3
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.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.}
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>
Quick View of ASP.NET MVC 3 Razor View Engine
ASP.NET MVC 3 introduces a new view-engine option called “Razor” which enables you to quickly integrate server code
into your HTML markup with a minimum of keystrokes. Unlike most template syntaxes, you do not need to interrupt your coding
to explicitly denote server blocks within your HTML. This enables a really compact and expressive syntax which is clean, fast and fun to type.
Here are the quick views related to Razor view-engine in asp.net MVC 3.0.
File Extension
.cshtml for c# and vbhtml for
vb.net
_(underscore)
Files that cannot be shown by
direct requests (master pages, partial views etc) have underscore (_) prefix
in their names. e.g. _Layout.cshtml
@
start of a server side code block.
It doesn’t require you to explicitly close the code-block. (short-hand of
<%= %>)
@{ code }
(Multi-line Statements) add
multiple lines of server side code by wrapping it within a @{ code } block.
@( )
(Multi-Token Statements) enables a
code block to have multiple tokens
@:
to explicitly indicate the start
of content in the line
<text>
to render multi-line content
blocks
layout page
asp.net master page is recognized
in MVC
Layout <file>
layout we want to use within a
ASP.NET MVC
@* comment *@
To define server side comment
(like <%– –%>) )
@RenderBody
used in layout where we want the
views based on this layout to “fill in” specific body content for a requested
URL.
@RenderSection
define two sections within our
layout that the view templates within our site can optionally choose to
fill-in
@section { }
To define section
@model <StrongModelType>
define strongly-typed models
@ViewBag.<myData>
New Dynamic Controller property,
It internally stores the property name/value pairs within the ViewData
dictionary. It is used to pass Data Between a Controller and a View
@tempdata
To pass State Between Action
Methods
Standard HTML Helpers(not a complete list)
* Html.ActionLink()
* Html.BeginForm()
* Html.CheckBox()
* Html.DropDownList()
* Html.EndForm()
* Html.Hidden()
* Html.ListBox()
* Html.Password()
* Html.RadioButton()
* Html.TextArea()
* Html.TextBox()
Other Helpers
Chart,
Crypto,
WebGrid,
WebImage,
WebMail, etc.
No comments:
Post a Comment