Professional Documents
Culture Documents
com) 1
BY
CALL :- 022-66752917
trainer@stepbystepschools.net
www.stepbystepschools.net
WHAT I DO? 8
MY SUCCESS 8
INTRODUCTION 10
TALK ABOUT VISUAL 10
WEB TECHNOLOGIES 10
VISUAL IN WEB 11
WHAT IS ASP.NET? 11
WHAT IS WEB FORMS? 11
ASP.NET 4.0 14
WHAT IS MVC? 14
WHAT IS ASP.NET MVC? 15
WHY ASP.NET WEB FORMS AND WHY ASP.NET MVC? 16
CONCLUSION 16
WHATS NEXT? 16
INTRODUCTION 25
STEP 1:- CREATE VIEWS 26
STEP 2:- CREATE CONTROLLER FOR THE VIEWS 26
INTRODUCTION 27
STEP 1:- OPEN THE GLOBAL.ASAX.CS FILE 27
STEP 2:- CUSTOMIZING THE URLS 28
STEP 3:- RUN THE APPLICATION 28
SO WHATS IN THE NEXT LAB 28
STEP 1:- INSTALL MVC 3 AND CREATE A PROJECT USING THE SAME 33
STEP 2:- SELECT RAZOR 33
STEP 3:- ADD A VIEW AND INVOKE THE SAME FROM CONTROLLER. 34
STEP 4:- PRACTICE RAZOR SYNTAXES 34
PRACTICE 1:- SINGLE LINE CODE 34
LAB 16:- SESSION MANAGEMENT IN MVC (VIEWDATA, VIEWBAG, TEMPDATA AND SESSION
VARIABLES) 41
UNDERSTANDING MINIFICATION 46
STEP 1:- CREATE A MVC PROJECT WITH EMPTY TEMPLATE 46
STEP 2:- CREATE A CONTROLLER WHICH INVOKES A VIEW 46
STEP 3:- RUN AND SEE HOW MULTIPLE CALLS ARE MADE. 46
STEP 4:- REFERENCING SYSTEM.WEB.OPTIMIZATION 47
STEP 5:- THE BUNDLECONFIG FILE 47
STEP 6:- CALL THE BUNDLE CONFIG FILE FROM GLOBAL.ASAX.CS FILE 47
STEP 7:- RENDER THE BUNDLES IN THE VIEW 48
STEP 8:- WATCH YOUR BUNDLING AND MINIFICATION IN REAL 48
INTERVIEW PREPARATION 59
As an author I wrote many online technical articles and won some awards for some of them.
This all started when I first met one of my greatest mentor ever Mr. Shivprasad Koirala. That meeting was about an open
source project on accounting.
I also started my CodeProject journey with Shiv sir writing my very first article about Mock Testing and after that I never looked
back.
From Basic C# Fundamentals to MVC, WCF, WPF, BI and Design patterns Shiv sir was there to guide me every time. He is purely
a down to earth person.
What I do?
I am Trainer.
I am Technical Leader.
I am News Paper publisher.
I am an author (CodeProject.com, CSharpCorner.com and www.justcompile.com).
I record videos for questpond.
Now I write books ;)
Most importantly I am learner
My Success
Complete success of this book and my professional career goes to several people.
First credit goes to my Mom and Dad without whom I would have done nothing. Their hard work and blessings took me
into this position.
My younger brother Suraj Marla He is not between us now. When he was around I never thought about hugging him
but now I want to but I cant. I cant do anything for him now but can try to keep his memories alive and can say only
one thing to him I miss you
My sister Ujjwala Kadu Thanks for all your support Ujju, Thanks for taking care of me, Thanks for each and everything
you did it my life. I cant even imagine a life without you.
My lovely wife Dipal Shah (Dipal Marla) In our 5+ yrs. of relation unlike most other wives she never expected too many
things from me. In fact, she supported me to get my goal and sacrificed many things. Thanks dear.
I would like to first start by thanking the two old eyes who made this person without any expectations, my dad and mom.
I have been very selfish to steal time from my kids (Sanjana, Simran and Aditya) and my wife ( Vishna) to complete this book.
So a big thanks to stand by me to ensure that this book comes alive.
I am blessed to have Raju as my brother who always keeps my momentum moving on.
Special thanks to Mr. Sukesh Marla with whom I had long fruitful technical discussion which has flown in the book and made
the book stronger.
Thanks to Mr.Shaam, Mr. Ajay and Miss Amrita for all the effort they have put in. It was their tiresome three months of support
that we have finally made it.
26 stunning labs with full details which starts right from simple hello world programs and then moves towards
complicated topics like view model and security.
50 great MVC interview questions quickly get ready for MVC interviews. Answers are crisp and to the point, great
collection for last minute revision.
Book also has a DVD accompanied which has step by step MVC videos which help you to visually see how the labs are
actually done.
Web world has come far away. Any server side technology today needs proper integration with JSON and JavaScript.
Dedicated labs on JSON, JQUERY integration with MVC showing every detail how to implement the same.
Performance is one of the key factors when it comes to MVC. A full step by step lab on bundling and Minification
which covers in detail steps of how we can increase MVC performance.
Session management in MVC is very different from ASP.NET Web forms. In MVC we have more fine tuning with
different session management techniques like tempdata , viewdata and viewbag. A full lab step by step explaining
how each one of these techniques varies.
One of the greatest strength of MVC is URL customization. We can customize MVC URL using MVC routing. Two great
labs which explains how MVC routing works and how to validations on the URL.
RAZOR is a new view engine created to simplify view creation. A full lab with details steps of how to create a RAZOR
view and different types of RAZOR syntaxes.
Security is one of the important aspects in any web application. Two detail labs which explains step by step how to do
forms and windows authentication / authorization in MVC.
Parallel execution is one the important features in web application for performance. MVC has introduced concept of
async controllers. A dedicated lab which explains how MVC async controllers can be implemented.
Two dedicated labs on MVC deployment and Exception handling takes the book to greater heights.
If you are thinking of learning MVC then you are at the right place. Its a complete book for learning MVC practically as
well as for preparing for interviews.
MVC is one of the most wanted skills and also complicated. The best way to learn such complicated skill is by going step by step
and doing things practically. In this book we have taken every feature of MVC and executed it step by step in form of 21 great
labs.
Every lab first starts with theory and understand and then goes step by step explaining the feature. Every lab is explained with
source code and print screens so that you do not miss out any details while executing the labs.
In case you miss out details we have also accompanied videos in the DVD so that you can know every step when you are doing
the practical. So start with the first Lab, get your mouse and keyboard running and if you are not able to understand something
start playing the videos for better understanding.
But thats not true. Both have their own pros and cons.
Nobody can tell or teach us what to use and when, but we can discuss about some facts which
will help us to make choice between both of them. This article does the same.
What is ASP.NET?
What is ASP.NET Web Forms?
What is MVC?
What is ASP.NET MVC?
If you already know the difference between MVC and Web Forms very well then this chapter will help you to revise your
concepts.
With the help of technologies like Visual Basic, Visual C++ Microsoft brought
up Visual into application development world.
In Visual world when we want to develop the UI we wont write much code
rater,
We will take some
controls from toolbox and place it the form
Position them in
the screen using mouse
Finally generate a code block in the code behind part which will respond
to specific user events.(Event driven programming)
In simple words it enabled RAD (rapid application development) of Graphical User applications. Features such as Drag and Drop
and intellisense made developers to focus more on the business functionality of the application rather than on UI design.
But this technique was limited to desktops, when it comes to web the only option left with Microsoft was ASP.
Web Technologies
When we say web technologies, we have classic ASP, php, jsp, ASP.NET Web Forms, ASP.NET MVC and many more.
Classic ASP is one of the web technology introduced by Microsoft. Biggest pain point with the classic ASP was spaghetti code
and Maintainability.
Let assume a scenario where you have some text boxes and a button. On button click you validate the data with the server and
if validation succeeds data will be stored into database and in case it fails, error message will be shown to user in the form of
red colored label.
You know whats the biggest problem with this scenario is? You have to do lots of stuffs by your own.
1. First make the self-post back by setting forms action attributes value to same page.
2. Text box values are going to be cleared on button click, so only choice left will be retrieving values from posted data.
3. In case validation fails you have to explicitly
a. Set all values back to the corresponding text boxes from posted data
b. Show error message.
(Using Ajax is an alternate method. Here I was trying to explain the manual work need to be done with classic ASP)
Visual in Web
In internet world there was no place for Event driven programming. It works on request/response pattern. End user will make a
request to server with the help of a client application called browser.
1. End user puts URL of the application in the address bar and press enter. It will make GET request to server.
2. Server will send back the response.
3. Response can be anything. It can be an image, a simple text or may be complex HTML.
4. If response is HTML and if it contains some submit buttons, when user click it, it will make a new POST request to
server.
5. Server will send the response again.
One thing which we should know about HTTP protocol is, its stateless. Server will treat every request as the new request. Once
the response is sent back it will just forget about the request.
Finally Microsoft came up with something called ASP.NET Web Forms, considering rapid application development and easy
learning in priority.
What is ASP.NET?
ASP.NET is a Microsofts Web application framework built on Common language runtime for building dynamic web sites using
one of the programming languages like C#, VB.NET etc.
It supports 2 models Web Forms and ASP.NET MVC.
Support for ViewState Stateless nature of HTTP normally clear values in the controls between multiple requests. But
in Web Forms statefulness is achieved by storing last known state of every control within the client page itself in the
form of hidden field called ViewState.
Event driven
programming
Disadvantages:
Unit Testing
In Web Forms code behind ends up with lots of event
handlers, making automatic unit testing an impossible
task.
Project Architecture
There is no fixed predefined Project Architecture for creating web applications when it comes to Web Forms.
Developers have full flexibility for choosing their own architecture.
One may use basic three layered architecture dividing the system into UI, Business layer and Data access layer or may
go with an advanced one like Model-View-Presenter. Even one may choose only code behind and write everything
there which is not at all considered as good practice.
Performance
ViewState became solution for some problems in classic ASP but it also brought up one new trouble. ViewState is
stored in the page itself effecting page size which in turn effects performance.
Reusability
Look at these examples I.
II. Lets say we want to build 2 User screens 1. Taxable Employee screen 2.
Nontaxable employee screen
Now most of the code behind logic is going to be same for both screens
One solution will be, add some if conditions in code behind and create a single UI.
This will violate SRP (Single Responsibility principle).
SRP says there should be only one reason because of which a software entity should get changed.
In above example employee form will be changed whenever any of the taxable/nontaxable information changes.
Less Control over HTML
In Web Forms many times we are not sure about what html we will get at the end making integration with JavaScript
frameworks like jQuery a difficult task.
SEO
ASP.NET 4.0
In ASP.NET 4.0 some good features were introduced to overcome some of the above problems
VewState: Provide the way to disable or control the size of the ViewState.
URL routing: Using URL routing we can provide our own URL in lieu of the physical path of the page.
ID: Now we have better control over Id of elements and thus integration with JavaScript framework become easier.
Even after the evolution of the revolutionary features of ASP.NET,
1. It was still not able to solve the problems of unit testing
2. We got some control over ID of elements, but not complete control over HTML.
What is MVC?
MVC is an architectural pattern which is has been around for sometimes now. Many are using it including Java. Its not a new
concept which Microsoft brought up. Before we go and talk about ASP.NET MVC lets clear out some terminologies.
Patterns
In simple words Pattern is a solution to a problem in a context.
Architectural Patterns
Architectural Pattern is something which solves our problem at sub system level/module level. It deals with the problem related
to architecture of a project. It explains us,
What all components should be there is the system? (Like UI, BAL, etc.)
How every component interact with each other?
What will be the entry point?
MVC
When we talk about application we will be having input logic, business logic and UI logic and MVC is an architectural pattern
which let us develop an application having loosely coupling between each of these elements.
The main intention behind MVC pattern is separation of concerns. It makes presentation
(UI) ignorant of business and user interaction logic.According to MVC system should be
divided as M (Model), V (View) and C (Controller).
Model is considered as smart and handles the
Business rules, logic and data and will be independent of other parts of MVC (controller
and View).
Controller receives and dispatches the request in
short it handles the user interaction and input logic. It knows about both Model and
View.
View is considered as dumb and is an output representation of model data. It may be an
excel sheet, a web page showing list of records or just a simple text. View knows about
only Model.
5. Controller chooses the appropriate view (like say Customer view which will may contain some html tables, drop downs,
textboxes).
6. Controller passes the data (model data retrieved in step 4) to chosen view (in step 5), where data will be populated as per
convenience.
7. Controller sends back view to the user.
(This was for get request, same happens for post. Only instead of putting URL in the browser user will do some action on
already requested page and flow start with controller.)
Why ASP.NET Web Forms and Why ASP.NET MVC?
Each can be the best choice for a particular solution depending on the requirements of the application and the background of
the developers involved. What to choose & when has more to do with business prospective than which one is better than
other.
Two important factors you should consider while making the choice is
1. Rapid application development -
When we want to develop something rapidly ASP.NET Web Forms is the best choice.
2. Unit testing or HTML - When automatic unit testing is the most important factor MVC is best. When our organization
has a group of talented HTML developers who will make UI for applications independently and we have to integrate
that UI to our final dynamic application, MVC is best, because in MVC we will get complete control over HTML.
Other than these, what you can do is, write down all your project requirement and try to compare them with Pros and Cons of
both Web Forms and MVC and if possible try to ask yourself some questions and point MVC and Web Forms accordingly.
Example -
1. Does your team have good experience with Web Forms or Windows Forms?
If yes then developers are already used to with ViewState and event driven programming now and migration to MVC
will be a difficult task. 1 point to Web Forms.
2. Does your team have experience on ASP or non-Microsoft technologies such as android, IOS, JSP, ROR or PHP?
MVC is a general architecture and so many are using it. Android, IOS, etc. by default works on MVC platforms.
In some web application development environment like PHP, JSP same request/response pattern is followed. Having
experience in one or more such technology will add one extra point to ASP.NET MVC.
3. Is JavaScript going to be used extensively?
If Yes, MVC gets the point because you get complete control over HTML. 1 point to ASP.NET MVC.
4. Looking for good performance?
If yes, 1 point to ASP.NET MVC.
5. Planning to reuse the same input/user interaction logic across multiple UI?
If yes, 1 point to MVC.
Conclusion
I think you should have equipped with enough information to make a decision what is best for your project. The complete
decision depends on your team and project requirement.
Whats next?
I think by now you would have got clear idea about Web Forms and MVC. So whats next? Lets do a step by step demo on MVC
and lets learn MVC from scratch. We will cover total 21 Labs. With each lab we will reach to a different level in MVC. You can
also find some videos about same labs in the DVD. Hope you will enjoy this journey. Wish you all the best.
Visual Studio 2010 or the free Visual Web Developer 2010 Express. These include ASP.NET MVC 2 template by default.
Visual Studio 2008 SP1 (any edition) or the free Visual Web Developer 2008 Express with SP1. These do not include
ASP.NET MVC 2 by default. You must also download and install ASP.NET MVC 2 from http://www.asp.net/mvc/ .
So once you have all your pre-requisite its time to start with the first lab.
Once you click ok, you have a readymade structure with appropriate
folders where you can add controllers, models and views.
Once you add the new controller you should see some kind of code snippet as shown in the below snippet.
Add view pops up a modal box to enter view name which will be invoked when
this controller action is called as shown in the figure below. For now keep the view
name same as the controller name and also uncheck the master page check box.
Once you click on the ok button of the view, you should see a simple ASPX page with
the below HTML code snippet. In the below HTML code snippet I have added This
is my first MVC application.
The problem with these object is the scope. ASP.NET session objects have session scope and view state has page scope. For
MVC we would like to see scope limited to controller and the view. In other words we would like to maintain data when the hit
comes to controller and reaches the view and after that the scope of the data should expire.
Thats where the new session management technique has been introduced in ASP.NET
MVC framework i.e. ViewData.
Create the class with 3 properties as shown in the below the code snippet.
public class Customer
{
public string Code
{set; get;}
public string Name
{set; get;}
public double Amount
{set; get;}
}
Step 2:- Define the controller with action
The next step is to add the controller and create a simple action display customer as shown in the below code snippet. Import
the model namespace in the controller class. In the action we created the object of the customer class, flourished with some
data and passed the same to a view named as DisplayCustomer.
public class CustomerController : Controller
{
..
.
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;
return View("DisplayCustomer",objCustomer);
}
}
Step 3:- Create strongly typed view using the class
We need to now join the points of MVC by creating views. So
right click on the view folder and click add view. You should see a
drop down as shown in the figure. Give a view name, check
create a strongly typed view and bind this view to the customer
class using the dropdown as shown in the figure.
The advantage of creating a strong typed view is you can now get the
properties of class in the view by typing the model and
. as shown in the figure.
Below is the view code which displays the customer property value.
We also have if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.
<body>
<div>
The customer id is <%= Model.Id %> <br />
</div>
</body>
Lots of manual code was written in the controller to flourish the object and send data to the MVC view.
public class CustomerController : Controller
{
[HttpPost]
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());
objCustomer.CustomerCode = Request.Form["Id"].ToString();
objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;
return View("DisplayCustomer", objCustomer);
}
}
In this lab we will see how to use MVC HTML helper classes to minimize the above manual code and increase productivity.
Step 1:- Create the Customer class
Create a simple customer class, please refer Lab 5 for the same.
Step 2:- Creating the input HTML form using helper classes
HTML helper classes have readymade functions by which you can create HTML
controls with ease. Go to any MVC view and see the intellisense for HTML helper class
you should see something as shown in the figure.
By using HTML helper class you can create any HTML control like textbox, labels, list
box etc. just by invoking the appropriate function.
In order to create the form tag for HTML we need to use Html.BeginForm.
<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post))
{%>
-- HTML input fields will go here
<%} %>
The above code will generate the below HTML
<form action="DisplayCustomer" method="post">
..
..
</form>
The HTML helpers beginform takes three input parameters action name (Method inside the controller), controller name
(actual controller name) and HTTP posting methodology (Post or GET).
If you want to create a text box, simply use the TextBox function of html helper class as shown in the below code. In this way
you can create any HTML controls using the HTML helper class functions.
Enter customer id :- <%= Html.TextBoxFor(x=>x.Id)%> <br />
The above code snippet will generate the below HTML code.
Enter customer id :- <input type="text" name="Id" /> <br />
To create a data entry screen like the one shown in figure we need to the use the below code snippet.
Step 3:- Create a strong typed view by using the customer class
So once you have created the view using the HTML helper classes its time to attach the customer class with view, please refer
lab 5 for the same.
[HttpPost]
public ActionResult DisplayCustomer(Customer obj)
{
return View(obj);
}
Enjoy your output for different condition
of customer amount entered.
Note - Many developers would talk about mock test, rhino mocks etc. but still its cryptic and the complication increases with
session variables, view data objects, ASP.NET UI controls creating further confusion.
So what we will do in this section is we will create a simple MVC application and we will do unit using VSTS unit test framework.
The controller class at the end of the day is a simple .NET class. For instance if you watch your project code closely, you can
easily see the customer controller class as shown below.
public class CustomerController : Controller
{
....
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;
return View("DisplayCustomer",objCustomer);
}
}
In simple words because this is a simple .NET class we can easily instantiate the class and create automated unit tests for the
same. Thats what exactly we are going to do in our next steps.
Note: In case you are a complete fresher to VSTS unit testing we would request to see the basic unit testing video from the DVD
where we have discussed how to unit test the simple .net class library.
Inside Test Method we are creating object of the controller class, invoking the controller action i.e. DisplayCustomer and then
checking if the view name is DisplayCustomer. If they are equal that means the test passes or else it fails.
[TestMethod]
public void DisplayCustomer()
{
CustomerController obj = new CustomerController();
var varresult = obj.DisplayCustomer();
Assert.AreEqual("DisplayCustomer", varresult.ViewName);
}
On the test view right click on the test and run the selected
test case as shown in the figure.
view. This bypasses your controller logic completely and your MVC architecture falls flat.
Ideally the actions should direct which page should be invoked. So the hyperlink should have actions in the anchor tags and not
the page names (view name).
This is products
<a href="GotoHome">Go Home</a><br />
<a href="Aboutus">About us</a><br />
If you want to create the anchor links using the HTML helper classes you can use the action link function as shown in the below
code snippet.
<%= Html.ActionLink("Home","Gotohome") %>
The above code was for the products page, you can do the same type of navigations for the about us and the home page.
This is About us
<a href="GotoHome">Go Home</a><br />
<a href="SeeProduct">See Product</a><br />
So for example if we have a controller class with name clsProductDetails and action as
getProduct , your URL ends up with a format
http://localhost/clsProductDetails/getProduct . Now how user friendly is that URL for
simple end users? - It is absolutely not.
MVC routing maps your browser URL request to the controllers and actions. So when
any request is sent to a MVC site it first hits the routing collection
and then depending on the values of URL appropriate
controller and action is invoked. By default MVC has a route
collection defined which maps the URL to default controller and
action name.
Lets go step by step exploring first the default routes provided and in the later steps we will customize the URL structure with
user friendly URL names.
You will see the below code which specifies default mappings:-
routes.MapRoute(
"Default", // Parameter 1
"{controller}/{action}/{id}", // Parameter - 2
new { controller = "Home", action = "Index", id = UrlParameter.Optional
}// - Parameter - 3
);
Parameter 1, Route key name: - The first value in the maproute function is the key name (name). This value identifies the
map in the collection using this keyname. This name should be unique throughout the collection.
Parameter 2, Route structure: - The second value in the maproute is the route structure. By default the value is "{controller}/
{action}/ {id}". This indicates that the user needs to send URL exactly like controller class name and action method name. The
last Id indicates that it can have input values as well.
Parameter 3, Controller and actions: - The third value specifies the controller class name and the action name which will
invoked depending on the URL structure provided. To provide controller and action names we need to specify new {controller
= "Home", action = "Index", id = UrlParameter.Optional}. In this syntax the controller specifies the controller name, action
specifies the action name and id specifies whether this parameter is compulsory or optional.
MVC framework provides a validation mechanism by which we can check on the URL itself if the data is appropriate. In this lab
we will see how to validate data which is entered on the MVC URL.
Customers.Add(obj1);
So in order to accommodate the numeric validation we need to the specify the regex constraint i.e. \d{1,2} in the maproute
function as shown below. \d{1,2} in regex means that the input should be numeric and should be maximum of length 1 or 2 ,
i.e. between 0 to 99.
You can specify default values by saying id=0 as shown in the below code snippet. So just in case if someone does not specify
the value to the id it will take the value as zero by default.
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer", id = 0 }, new { id =
@"\d{1,2}" }); // Parameter defaults
If you try to specify value more than 100 you would get error as shown below. Please note that the error is confusing but its
the effect of the regex validation which is specified on the maproute function.
If you try to specify a non-numeric value you should again get the same error which confirms that our regex validation is
working properly.
The most important point to note is that these validations are executed even before the request reaches the controller
functions.
So you would probably like to write the validation once and then expect the validation framework to generate the validation
logic on both the ends.
In MVC you validate model values. So once the data comes inside the model you would like to question the model saying, is the
data provided proper? Are values in range? etc.
Data annotations are nothing but the metadata which you can apply on the model and the MVC framework will validate using
the metadata provided.
In this lab lets enforce validation by using data annotation. So the first thing is use Lab 4 and create a simple model and a
strong typed data entry view.
So assuming you have created the model and the strong typed view, lets start applying data annotations.
Let say we have a customer model and we want to ensure that the customer code field is compulsory. So you can apply
attribute Required as shown in the below code snippet. If the validation fails and you would like to display some error
message, you can pass the ErrorMessage also.
public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
We also need to our HTML form to input data. Below is the code snippet for the same
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>
In case you want to use regular expression, you can use RegularExpression attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
If you want to check whether the numbers are in range, you can use the Range attribute.
[Range(10,25)]
public int Age { get; set; }
Some time you would like to compare value of one field with other field, we can use the Compare attribute.
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }
In case you want to get a particular error message, you can use the Errors collection.
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the object
is valid or not.
TryUpdateModel(NewCustomer);
In case you want add errors in the controller you can use AddModelError function.
ModelState.AddModelError("FirstName", "This is my server-side error.");
In case you have not installed MVC 3 template, you can get it from
http://www.asp.net/mvc/mvc3
Developers demanded for a clean, light weight view and with less
syntactic noise: - Answer was RAZOR.
So lets create a simple lab to demonstrate use of Razor views.
Step 1:- Install MVC 3 and create a project using the same
Install MVC 3 template from http://www.asp.net/mvc/mvc3 and create a project selecting the MVC 3 template below.
For now lets keep life simple and lets select the empty option. The
second thing which we need to select is what kind of view we want, so
lets select Razor and move ahead.
Once the project is created you can see the Razor file with the name .cshtml. Now the
_ViewStart page is nothing but its a common page which will be used by views for
common things like layouting and common code.
Step 3:- Add a view and invoke the same from controller.
Now go ahead and add a new view and invoke this view from the
controller. Adding and invoking the view from controller remains same as
discussed in the previous labs. Just remember to select the view as Razor
view.
If you compare the above syntax with ASPX view you need to type the below code, so isnt
the syntax much simpler, neat and light weight.
<%= DateTime.Now%>
@if (DateTime.Now.Year.Equals(2011))
{
// Some code here
}
But no worries razor team has taken care of it. You can use the Html.Raw to display the same as shown in the below code
snippet.
@{
var link = "<a href='http://www.questpond.com'>
Click here</a>";
}
@Html.Raw(link);
Now one way to implement windows authentication is by creating project using the intranet application option. As said
previously intranet application option is enabled to authenticate users from windows active directory.
For now we will not use the empty application option and create from scratch so that we can understand better.
<authorization>
<deny users="?"/>
</authorization>
Step 2:- Just some defects
In MVC 3 template there is a small defect. It runs the forms authentication by default. Set the below tags in appsettings tag to
avoid problems. It took me 2 hours to figure this out, what a waste.
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
</appSettings>
In the next screen its will prompt which dependencies you want to include.
For now I have razor view so I
have selected both the
options.
Once you can see the dependent DLLs been added to the project.
This HTML form is making a post to the action Login which is currently in Home controller and its using HTTP POST method.
So when the user presses submit, it will hit the Login action. The next thing after this is to create the Login action which will
validate the username and password.
Once we have checked the credentials the next step is to use the famous FormsAuthentication class and set the cookie saying
that this user is proper.
So that in the next request when the user comes he will not be validated again and again. After the cookie is set redirect to the
About view or else just stand on the Index view.
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<div>
This is About us
</div>
</body>
</html>
So if any user who is unauthorized, directly hits any one of these controllers they will be sent back to the Index view i.e. back
to Login screen.
[Authorize]
public ActionResult Default()
{
return View();
}
[Authorize]
public ActionResult About()
{
return View();
}
Normally in ASP.NET this login URL points to an ASP.NET page, but in MVC it points to an action i.e. /Home/Index. This action
invokes the login credentials page.
<authentication mode="Forms">
<forms loginUrl="~/Home/Index" timeout="2880"/>
</authentication>
For this lab please ensure that the project is created by using basic project template so
that the necessary JQuery libraries are included with the MVC project.
The next step is to consume the JSON data in jQuery using MVC view. So go ahead and add a view for example my view name is
LearnJquery.aspx.
First thing add the jQuery library at the top of the ASPX page. In case you do not find jQuery library in your project that means
you have not created the MVC project using the basic template.
<script src="../../Scripts/jquery-1.8.2.js"></script>
You can then make a call the controller which is exposing in JSON format using getJson method as shown below. Its takes
three parameters:-
The first parameter in getJson is the MVC JSON URL with complete controller/action path format.
The second parameter is the data to be passed. For now its NULL as we are more interesting in getting JSON data
rather posting data.
The last parameter is the call back method (Display) which will be invoked once we get the JSON data from the
controller. The Display function is also available in the below code snippet. I am just putting an alert with the
property name. FYI you can see how I have just typed data.CustomerCode , no parsing nothing the JSON data is
automatically translated to javascript object.
$.getJSON("/Json/getJson", null, Display);
function Display(data)
{
alert(data.CustomerCode);
}
The complete MVC view HTML looks as shown below. I have created a simple HTML button and on the click event I am calling a
getJson JavaScript method which makes a call to the JSON controller and displays the JSON data in a JavaScript alert.
<script language="javascript">
function getJson() {
return View("LearnJquery");
}
}
Step 4:- Run the application and see the data
After you have done all the hardwork its time to hit the DisplayJson action to see the beauty running.
Lab 16:- Session management in MVC (ViewData, ViewBag, TempData and session variables)
The primary goal of MVC is to create web applications and web applications use HTTP protocol. Now HTTP protocol is a
stateless by nature. So when you send a request to MVC application it serves the request and forgets about the request. Next
time when the same user sends the request MVC treats that as a complete new request.
In short we need to have some kind of mechanism which will help us to remember states between request and response of
MVC.
There are 3 ways of maintaining states in MVC and these ways can be used depending from which layer to which layer you
navigate.
Temp data: - Helps to maintain data on redirects for a single request and
response. Now the redirects can be from controller to controller or from
controller to view.
View data: - Helps to maintain data when you move from controller to view.
Session variables: - By using session variables we can maintain data until the browser closes.
The SomeView view just displays the data present in TempData ,ViewData , ViewBag and Session .
<%= TempData["FortheFullRequest"] %> <br />
<%= ViewData["Myval"] %><br />
<%= Session["Session1"] %>
<%= ViewBag.MyVal %>
<a href="/Default1/Action1">Click</a>
So lets put debug points in both the controller actions and lets hit
Default1 controller and Action1 action
http://localhost:1203/Default1/Action1 . So in this action session,
tempdata , viewdata and viewbag are loaded. Below is how the
watch window looks with data.
When the view gets invoked we can see all the data. In
other words ViewData and ViewBag persist data from
controller to view. And also tempdata and session have
persisted data.
As you can see in the view we have a simple hyper link which will invoke
ActionNew in ControllerNew action.
When we click on
the link. All the other variables go off only session variables persist,
see the below figure. It means Session variables can persist
between requests
So lets say first request comes to the site, IIS pulls up a readymade thread object from the thread pool and starts serving that
request. In the meantime lets say second request comes in so again IIS pulls up a thread from the thread pool and starts
serving the second request.
Now the fun starts when third request comes in. The IIS webserver does not have any more thread objects in the pool as those
are already serving request1 and request2. So he just moves the third request in to a waiting mode or the server can send
503 busy message to the client.
This situation is termed as Thread Starvation. Thread starvation situations can be overcome by making the request
Asynchronous. So the request comes in and immediately the request is processed in an Asynch manner and releasing the
thread serving the request immediately.
So to avoid this we can achieve the same by making our controllers Asynch.
Note: Please watch the video from DVD and learn more about MVC Thread starvation.
The heavy logic code i.e. Thread.Sleep is moved to a different method and that method is invoked using task parallel library
from the SomeHeavyMethodAsync.
Every time a Task or a Thread is started we increment the outstanding operations counter by using AsynchManager and
every time a multi-threaded task is completed we decrement the counter.
public class HeavyController : AsyncController
{
public void SomeHeavyMethodAsync()
{
AsyncManager.OutstandingOperations.Increment();
Task.Run(new Action(Heavy));
}
public void Heavy()
{
Thread.Sleep(20000);
AsyncManager.OutstandingOperations.Decrement();
}
}
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Some heavy method</title>
</head>
<body>
<div>
This is loaded after some time....
</div>
</body>
</html>
Understanding Bundling
Web projects always need CSS and script files. Bundling helps us to
combine multiple JavaScript or CSS files into a single entity during
runtime thus combining multiple requests in to a single request which
in turn helps to improve performance.
For example consider the below web request to a page. (Note: request
are recorded by using chrome developer tools.) This page consumes
two JavaScript files Javascript1.js and Javascript2.js. So when this
page is requested it makes three request calls:-
Just try to imagine a situation when we have lots of JavaScript file. It leads to multiple requests thus decreases performance.
Solution will be combine all the JS files into single bundle and request it in a single request as a single unit. This process is
termed as bundling.
Understanding Minification
Minification reduces the size of script and CSS files by removing blank spaces, comments etc. For example below is a simple
JavaScript code with comments.
// This is test
var x = 0;
x = x + 1;
x = x * 2;
After implementing Minification the JavaScript code looks something as below. You can see how whitespaces and comments
are removed to minimize file size and thus increasing performance as the file size has become smaller and compressed.
var x=0;x=x+1;x=x*2;
So lets demonstrate a simple example of bundling and Minification with MVC 4.0 step by step.
Step 1:- Create a MVC project with Empty template
So to understand bundling and Minification, lets go ahead and create an empty MVC project. In
that lets add a Script folder and insideScript folder , lets add two javascript files as shown in
the below figure.
Step 3:- Run and see how multiple calls are made.
Now run the MVC application in Google chrome, press CNTRL + SHIFT + I keyboard keys to see the below output.
You can see there are three requests:-
Note: In DVD we have added one video about NUGET in detail. If you are willing to learn NUGET in detail please go through it
Step 6:- Call the bundle config file from global.asax.cs file
Open the global.asax.cs file and in the application start call the RegisterBundles method as shown in the below code.
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
Below is the complete bundling code called inside the MVC view?
<%= System.Web.Optimization.Scripts.Render("~/Bundles") %>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>MyView</title>
</head>
<body>
<div>
This is a view.
</div>
</body>
</html>
Step 8:- Watch your Bundling and Minification in real
So now that you are all set, its time to see the bundling and Minification in
real. So run google chrome, press CNTRL + SHIFT + I and you can see the
magic there is only one call for both the JavaScript files.
If you click on the preview tab you can see both the JavaScript files have
been unified and. GUESS, yes Minification has also taken place.
But when this Customer model object is displayed on the MVC view it
looks something as shown in the figure. It has CustomerName, Amount
plus Customer Buying Level fields on the view / screen. Customer buying
Level is a color indication which indicates how aggressive the customer is
in buying.
Customer buying level color depends on the value of the Amount property. If the amount is greater than 2000 then color is
red, if amount is greater than 1500 but less than 200 then color is orange or else the color is yellow.
In other words Customer buying level is an extra property which is calculated on the basis of amount.
Color transformation logic: - For example you have a Grade property in model and you would like your UI to display
red color for high level grade, yellow color for low level grade and green color of ok grade.
Data format transformation logic: - Your model has a property Status with Married and Unmarried value. In
the UI you would like to display it as a checkbox which is checked if married and unchecked if unmarried. (In short
we want Boolean value in return).
Aggregation logic: - You have two different Customer and Address model classes and you have view which displays
both Customer and Address data on one go.
Structure downsizing logic: - You have Customer model with customerCode and CustomerName and you want
to display just CustomerName. So you can create a wrapper around model and expose the necessary properties.
Lets do a small lab to understand MVC view model concept using the scenario
discussed previously.
Below are some important points to note about the view model class:-
You can see in the below class how CustomerViewModel class wraps
CustomerModel class.
Now for the most important, watch the code for CustomerLevelColor property, it displays color depending on the
amount of customer sales.
public class CustomerViewModel
{
private CustomerModel Customer = new CustomerModel();
public string TxtName
{
get { return Customer.CustomerName; }
set { Customer.CustomerName = value; }
}
public string TxtAmount
{
get { return Customer.Amount.ToString(); }
set { Customer.Amount = Convert.ToDouble(value); }
}
If you see the view it is now decorated or you can say binded with view model class.
The most important thing to watch is your view is CLEAN. It does not have decision
making code for color coding. Those gel codes have gone inside the view model class.
This is what makes VIEW MODEL a very essential component of MVC.
<table class="auto-style1">
<tr>
<td class="auto-style2">Customer Name :-</td>
<td class="auto-style3"> <%= Model.TxtName %></td>
</tr>
<tr>
<td class="auto-style2">Amount</td>
<td class="auto-style3"><%= Model.TxtName %></td>
</tr>
<tr>
<td class="auto-style2">Customer buying level</td>
<td class="auto-style3"><div style="background-color: <%=
Model.CustomerLevelColor %>; width: 228px; height: 27px;"></td>
</tr>
</table>
This view can be invoked from a controller which passes some dummy data as shown in the below code.
public class CustomerController : Controller
{
//
// GET: /Customer/
obj.Customer.Amount = 1000;
return View(obj);
}
So why does composition make more sense? If you visualize we never say This Screen is a child of Business objects, that
would be a weird statement.
We always say This screen uses those models. So its very clear its a using relationship and not an IS A (child parent)
relationship.
When you DO NOT want some properties from the model in your view
When you have a view which uses multiple models.
So do not get lured with the thought of creating a view model by inheriting from a model you can end up in to a LISKOV issue
It looks like a duck, quacks like a duck but it is not a duck. It looks like a model has properties like a model but it is not exactly a
model.
Advantages of VM
Reusability: - Now that my gel code has come in to a class. I can create the object of that class in any other UI
technology (WPF, Windows etc.) easily.
Testing: - We do not need manual testers to test the UI look and feel now. Because our UI code has moved in to a
class library (least denominator) we can create an object of that class and do unit testing. Below is a simple unit test
code which demonstrates unit testing of UI look and feel logic. You can see how the color testing is done
automatically rather than some manual tester testing it manually.
[TestMethod]
public void TestCustomerLevelColor()
{
CustomerViewModel obj = new CustomerViewModel();
obj.TxtName = "Shiv";
obj.TxtAmount = "1000";
Assert.AreEqual("Red",obj.CustomerLevelColor);
}
Output
It seems that only step 1 done all the work, but how? We have not specified the error page (view) name anywhere, still in
response we get error view whenever error occurs. Lets understand how?
FilterConfig class
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
What it does?
It handles all the exceptions raised by all action methods in all the controllers and return error view present inside shared
folder.
Now errors raised by all action methods present inside TestingController method will be handled. Other exceptions will be
considered as unhandled exceptions.
Limitations of HandleErrorAttribute
1. Error wont get logged anywhere.
2. Exceptions raised outside controllers will not be handled. Example- exception raised because of invalid url wont be
handled.
3. Exception Handling based on scenario is not possible. Example So one error page when request comes via ajax and
different one when comes via normal request.
Extending HandleErrorAttribute
Some of the above limitations can be overcame by extending the default HandleErrorAttribute as follow.
public class MyExceptionFilter: HandleErrorAttribute
{
private bool IsAjax(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["X-Requested-With"] ==
"XMLHttpRequest";
}
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled ||
!filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
As you can see nothing is organized. When it comes to code management it will be very
difficult.
Above image is the structure of the project when we had 2 modules, imagine a
situation when we have hundreds of modules in single system.
Just like real world we use the concept of area in Asp.Net MVC to break single system into modules. One area represents one
module by means of logical grouping of controllers, Models and Views.
How to use Areas?
Step1 Right click your project and say Add>>Area
Note: Area is logical grouping not physical, so no separate dlls will be created for every
area.
In order to achieve same functionality using simple folder you have to do following
things.
1. Create module structure manually.
a. One folder for every module.
b. Three Folder inside every module folder naming Controller, Models
and Views.
c. One Web.Config file for every module (to store settings related to
that module).
2. Create one custom route for every module Controllers.
3. Create Custom View Engine for every module which will search for the view in customized locations instead of
predefined locations (Views/{Controlles} or Views/Shared )
Default View Search
Interview Preparation
What is MVC?
MVC is an architectural pattern which separates the representation and the user interaction.
Its divided in to three broader sections, Model, View and Controller. Below is how
each one of them handles the task.
The View is responsible for look and feel.
Model represents the real world object and provides data to the View.
The Controller is responsible to take the end user request and load the
appropriate Model and View.
Below is Html.TextBoxFor code which creates HTML textbox using the property name CustomerCode from object m.
Html.TextBoxFor(m => m.CustomerCode)
In the same way we have for other HTML controls like for checkbox we have Html.CheckBox and Html.CheckBoxFor.
For instance lets say we want that when any user types http://localhost/View/ViewCustomer/ , it goes to the Customer
Controller and invokes DisplayCustomer action. This is defined by adding an entry in to the routes collection using the
maproute function. Below is the under lined code which shows how the URL structure and mapping with controller and
action is defined.
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer", id =
UrlParameter.Optional }); // Parameter defaults
How can we navigate from one view to other view using hyperlink?
By using ActionLink method as shown in the below code. The below code will create a simple URL which help to navigate to
the Home controller and invoke the GotoHome action.
<%= Html.ActionLink("Home","Gotohome") %>
View data: - Helps to maintain data when you move from controller to view.
View Bag: - Its a dynamic wrapper around view data. When you use
Viewbag type casting is not required. It uses the dynamic keyword
internally.
Session variables: - By using session variables we can maintain data from any
entity to any entity.
Hidden fields and HTML controls: - Helps to maintain data from UI to controller only. So you can send data from HTML controls
or hidden fields to the controller using POST or GET HTTP methods.
view.
How did you create partial view and consume the same?
When you add a view to your project you need to check the Create partial view check box.
Once the partial view is created you can then call the partial view in the main
view using Html.RenderPartial method as shown in the below code snippet.
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
ThisCustomerCode property is tagged with a Required data annotation attribute. In other words if this model is not
provided customer code it will not accept the same.
public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
In order to display the validation error message we need to use ValidateMessageFor method which belongs to the Html
helper class.
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>
Later in the controller we can check if the model is proper or not by using ModelState.IsValid property and accordingly we
can take actions.
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
Below is a simple view of how the error message is displayed on the view.
What are the other data annotation attributes for validation in MVC?
If you want to check string length, you can use StringLength.
[StringLength(160)]
public string FirstName { get; set; }
In case you want to use regular expression, you can use RegularExpression attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
If you want to check whether the numbers are in range, you can use the Range attribute.
[Range(10,25)]
public int Age { get; set; }
Some time you would like to compare value of one field with other field, we can use the Compare attribute.
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }
In case you want to get a particular error message, you can use the Errors collection.
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the object
is valid or not.
TryUpdateModel(NewCustomer);
In case you want add errors in the controller you can use AddModelError function.
ModelState.AddModelError("FirstName", "This is my server-side error.");
You can add an area by right clicking on the MVC solution and clicking on Area menu as shown in the below figure.
In the image we have two Areas created Account and Invoicing and in that I
have put the respective controllers. You can see how the project is looking more
organized as compared to the previous state.
<%=DateTime.Now%>
In Razor its just one line of code.
@DateTime.Now
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
Then in the controller or on the action you can use the Authorize attribute which specifies which users have access to these
controllers and actions. Below is the code snippet for the same. Now only the users specified in the controller and action can
access the same.
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
We also need to create a controller where we will check the user is proper or not. If the user is proper we will set the cookie
value.
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] ==
"Shiv@123"))
{
FormsAuthentication.SetAuthCookie("Shiv",true);
return View("About");
}
else
{
return View("Index");
}
}
All the other actions need to be attributed with Authorize attribute so that any unauthorized user if he makes a call to these
controllers it will redirect to the controller ( in this case the controller is Login) which will do authentication.
[Authorize]
publicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}
Below is a simple sample of how to implement Ajax by using Ajax helper library. In the below code you can see we have a
simple form which is created by using Ajax.BeginForm syntax. This form calls a controller action called as getCustomer. So
now the submit action click will be an asynchronous Ajax call.
<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<div>
<%
var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>
In case you want to make ajax calls on hyperlink clicks you can use Ajax.ActionLink
function as shown in the image.
So if you want to create Ajax asynchronous hyperlink by name GetDate which calls the
GetDate function on the controller, below is the code for the same. Once the controller
responds this data is displayed in the HTML DIV tag by name DateDiv.
Below is the controller code. You can see how GetDate function has a pause of 10 seconds.
public class Default1Controller : Controller
{
The second way of making Ajax call in MVC is by using Jquery. In the below code you can see we are making an ajax POST call to
a URL /MyAjax/getCustomer. This is done by using $.post. All this logic is put in to a function called as GetData and you
can make a call to the GetData function on a button or a hyper link click event as you want.
function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
})
}
ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically
ActionResult is the best thing. For example in the below code snippet you can see we have a simple action called as
DynamicView. Depending on the flag (IsHtmlView) it will either return ViewResult or JsonResult.
There 12 kinds of results in MVC, at the top is ActionResult class which is a base class that can have 11subtypessas listed
below
1. ViewResult - Renders a specified view to the response stream
2. PartialViewResult - Renders a specified partial view to the response stream
3. EmptyResult - An empty response is returned
4. RedirectResult - Performs an HTTP redirection to a specified URL
5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on
given route data
6. JsonResult - Serializes a given ViewData object to JSON format
7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
8. ContentResult - Writes content to the response stream without requiring a view
9. FileContentResult - Returns a file to the client
10. FileStreamResult - Returns a file to the client, which is provided by a Stream
11. FilePathResult - Returns a file to the client
To create an inline action attribute we need to implement IActionFilter interface.The IActionFilter interface has two
methods OnActionExecuted and OnActionExecuting. We can implement pre-processing logic or cancellation logic in these
methods.
The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter
to an action filter attribute. To create an action filter attribute we need to inherit from ActionFilterAttribute and implement
IActionFilter interface as shown in the below code.
public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action executing");
}
}
Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have
decorated the Default1Controller with MyActionAttribute class which was created in the previous code.
[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}
Let say we want to create a custom view engine where in the user can type a command like <DateTime> and it should display
the current date and time.
Step 1:- We need to create a class which implements IView interface. In this class we should write the logic of how the view
will be rendered in the render function. Below is a simple code snippet for the same.
public class MyCustomView : IView
{
Step 2:-We need to create a class which inherits from VirtualPathProviderViewEngine and in this class we need to provide the
folder path and the extension of the view name. For instance for razor the extension is cshtml, for aspx the view extension is
.aspx, so in the same way for our custom view we need to provide an extension. Below is how the code looks like. You can see
the ViewLocationFormats is set to the Views folder and the extension is .myview.
public class MyViewEngineProvider : VirtualPathProviderViewEngine
{
// We will create the object of Mycustome view
public MyViewEngineProvider() // constructor
{
// Define the location of the View file
this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview",
"~/Views/Shared/{0}.myview" }; //location and extension of our views
}
Step 3:- We need to register the view in the custom view collection. The best place to register the custom view engine in the
ViewEngines collection is the global.asax file. Below is the code snippet for the same.
protected void Application_Start()
{
// Step3 :- register this object in the view engine collection
ViewEngines.Engines.Add(new MyViewEngineProvider());
..
}
Below is a simple output of the custom view written using the commands defined at the top.
Below is the JSON output of the above code if you invoke the
action via the browser.
What is WebAPI?
HTTP is the most used protocol. For past many years browser was the most preferred client by which we can consume data
exposed over HTTP. But as years passed by client variety started spreading out. We have demand to consume data on HTTP
from clients like mobile, JavaScript, windows application etc.
For satisfying the broad range of client REST was the proposed approach.
WebAPI is the technology by which you can expose data over HTTP following REST principles.
But WCF SOAP also does the same thing, so how does WebAPI differ?
Size Heavy weight because of complicated WSDL structure. Light weight, only the necessary information is
transferred.
Formats To parse SOAP message, the client needs to understand Output of WebAPI are simple string message,
WSDL format. Writing custom code for parsing WSDL is a JSON, Simple XML format etc. So writing parsing
heavy duty task. If your client is smart enough to create logic for the same in very easy.
proxy objects like how we have in .NET (add reference)
then SOAP is easier to consume and call.
Principles SOAP follows WS-* specification. WEB API follows REST principles. (Please refer
about REST in WCF chapter).
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
Step 3:-If you make a HTTP GET call you should get the below results.
Minification reduces the size of script and CSS files by removing blank spaces, comments etc. For example below is a simple
JavaScript code with comments.
MVC wont ends up here. We have to include one more layer in this architecture that is View Model. View Model will act as an
intermediary between Model and View.
In View Model is View specific data. Controller when receives the request, Get the data in form of Model and then convert it
into View Model and then bind it to view.
View Model may contain Color transformation logic, Data format transformation logic, Aggregation logic, Structure downsizing
logic
But you can bypass this restriction by using one of the following 2 attributes
1) ValidateInput attribute at controller level or action level
In unobtrusive approach we write JavaScript in such a way that button JavaScript code will be decoupled from the buttons html
markup. It makes us change the behavior later in the stage without touching the markup.
<script>
function ShowAlert()
{
alert("Hello");
}
var el = document.getElementById("btn");
el.onclick = ShowAlert;
</script>