What Is MVC (Model View Controller) ?

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 105

ASP.

NET MVC interview questions with answers

What is MVC (Model View Controller)?


MVC is an architectural pattern which separates the representation and user interaction. It’s divided
into three broader sections, Model, View, and Controller. Below is how each one of them handles the
task.

 The View is responsible for the look and feel.


 Model represents the real world object and provides data to the View.
 The Controller is responsible for taking the end user request and loading the appropriate Model and
View.

Figure: MVC (Model view controller)

Explain MVC application life cycle?


There are six broader events which occur in MVC application life cycle below diagrams summarize it.
Any web application has two main execution steps first understanding the request and depending on
the type of the request sending out appropriate response. MVC application life cycle is not different
it has two main phases first creating the request object and second sending our response to the
browser.
Creating the request object: -The request object creation has four major steps. Below is the detail
explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller
and action to be invoked. So if the request is the first request the first thing is to fill the route table
with routes collection. This filling of route table happens in the global.asax file.
Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table to
create “RouteData” object which has the details of which controller and action to invoke.
Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext”
object.
Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create
the controller class instance. Once the controller class object is created it calls the “Execute” method
of the controller class.
Creating Response object: - This phase has two steps executing the action and finally sending the
response as a result to the view.

Is MVC suitable for both Windows and Web


applications?
The MVC architecture is suited for a web application than Windows. For Window applications, MVP,
i.e., “Model View Presenter” is more applicable. If you are using WPF and Silverlight, MVVM is more
suitable due to bindings.

What are the benefits of using MVC?


There are two big benefits of MVC:
 Separation of concerns is achieved as we are moving the code-behind to a separate class file. By
moving the binding code to a separate class file we can reuse the code to a great extent.

 Automated UI testing is possible because now the behind code (UI interaction code) has moved to a
simple .NET class. This gives us opportunity to write unit tests and automate manual testing.

Is MVC different from a three layered


architecture?
MVC is an evolution of a three layered traditional architecture. Many components of the three
layered architecture are part of MVC. So below is how the mapping goes:

Three layered / tiered


Functionality Model view controller architecture
architecture

Look and Feel User interface View

UI logic User interface Controller

Business logic
Middle layer Model
/validations

Request is first sent to User interface Controller

Accessing data Data access layer Data Access Layer


Figure: Three layered architecture

What is the latest version of MVC?


MVC 6 is the latest version which is also termed as ASP VNEXT.

What is the difference between each version of


MVC 2, 3 , 4, 5 and 6?
MVC 6

ASP.NET MVC and Web API has been merged in to one.

Dependency injection is inbuilt and part of MVC.

Side by side - deploy the runtime and framework with your application

Everything packaged with NuGet, Including the .NET runtime itself.

New JSON based project structure.

No need to recompile for every change. Just hit save and refresh the browser.
Compilation done with the new Roslyn real-time compiler.

vNext is Open Source via the .NET Foundation and is taking public contributions.

vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.

MVC 5

One ASP.NET

Attribute based routing

Asp.Net Identity

Bootstrap in the MVC template

Authentication Filters

Filter overrides

MVC 4

ASP.NET Web API

Refreshed and modernized default project templates

New mobile project template

Many new features to support mobile apps

Enhanced support for asynchronous methods

MVC 3

Razor

Readymade project templates

HTML 5 enabled templates

Support for Multiple View Engines

JavaScript and Ajax

Model Validation Improvements


MVC 2

Client-Side Validation

Templated Helpers

Areas

Asynchronous Controllers

Html.ValidationSummary Helper Method

DefaultValueAttribute in Action-Method Parameters

Binding Binary Data with Model Binders

DataAnnotations Attributes

Model-Validator Providers

New RequireHttpsAttribute Action Filter

Templated Helpers

Display Model-Level Errors

What are HTML helpers in MVC?


HTML helpers help you to render HTML controls in the view. For instance if you want to display a
HTML textbox on the view , below is the HTML helper code.

Hide   Copy Code

<%= Html.TextBox("LastName") %>

For checkbox below is the HTML helper code. In this way we have HTML helper methods for every
HTML control that exists.

Hide   Copy Code

<%= Html.CheckBox("Married") %>


What is the difference between “HTML.TextBox”
vs “HTML.TextBoxFor”?
Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while
“HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple textbox with
“CustomerCode” as name.

Hide   Copy Code

Html.TextBox("CustomerCode")

Below is “Html.TextBoxFor” code which creates HTML textbox using the property name
‘CustomerCode” from object “m”.

Hide   Copy Code

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”.

What is routing in MVC?


Routing helps you to define a URL structure and map the URL with the controller.

For instance let’s say we want that when a user types “http://localhost/View/ViewCustomer/”, it goes
to the “Customer” Controller and invokes the DisplayCustomer action. This is defined by adding
an entry in to the routes collection using the maproute function. Below is the underlined code
which shows how the URL structure and mapping with controller and action is defined.
Hide   Copy Code

routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults

Where is the route mapping code written?


The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax"
application start event.
Can we map multiple URL’s to the same action?
Yes, you can, you just need to make two entries with different key names and specify the same
controller and action.

Explain attribute based routing in MVC?


This is a feature introduced in MVC 5. By using the "Route" attribute we can define the URL structure.
For example in the below code we have decorated the "GotoAbout" action with the route attribute.
The route attribute says that the "GotoAbout" can be invoked using the URL structure "Users/about".

Hide   Copy Code

public class HomeController : Controller


{
[Route("Users/about")]
public ActionResult GotoAbout()
{
return View();
}
}

What is the advantage of defining route


structures in the code?
Most of the time developers code in the action methods. Developers can see the URL structure right
upfront rather than going to the “routeconfig.cs” and see the lengthy codes. For instance in the
below code the developer can see right upfront that the “GotoAbout” action can be invoked by four
different URL structure.

This is much user friendly as compared to scrolling through the “routeconfig.cs” file and going
through the length line of code to figure out which URL structure is mapped to which action.

Hide   Copy Code

public class HomeController : Controller


{
[Route("Users/about")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout()
{
return View();
}
}

How can we navigate from one view to another


using a hyperlink?
By using the ActionLink method as shown in the below code. The below code will create a simple
URL which helps to navigate to the “Home” controller and invoke the GotoHome action.
Hide   Copy Code

<%= Html.ActionLink("Home","Gotohome") %>

How can we restrict MVC actions to be invoked


only by GET or POST?
We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of
HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can
only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an
error.
Hide   Copy Code

[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}

How can we maintain sessions in MVC?


Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.
What is the difference between tempdata,
viewdata, and viewbag?

Figure: Difference between tempdata, viewdata, and viewbag

 Temp data - Helps to maintain data when you move from one controller to another controller or
from one action to another action. In other words when you redirect, tempdata helps to maintain
data between those redirects. It internally uses session variables.
 View data - Helps to maintain data when you move from controller to view.
 View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not
required. It uses the dynamic keyword internally.
Figure: dynamic keyword

 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.

Below is a summary table which shows the different mechanisms for persistence.

Maintains data
ViewData/ViewBag TempData Hidden fields Session
between

Controller to
No Yes No Yes
Controller

Controller to View Yes No No Yes

View to Controller No No Yes Yes

What is difference between TempData and


ViewData ?
“TempData” maintains data for the complete request while “ViewData” maintains data only from
Controller to the view.
Does “TempData” preserve data in the next
request also?
“TempData” is available through out for the current request and in the subsequent request it’s
available depending on whether “TempData” is read or not.

So if “TempData” is once read it will not be available in the subsequent request.

What is the use of Keep and Peek in


“TempData”?
Once “TempData” is read in the current request it’s not available in the subsequent request. If we
want “TempData” to be read and also available in the subsequent request then after reading we
need to call “Keep” method as shown in the code below.

Hide   Copy Code

@TempData[&ldquo;MyData&rdquo;];
TempData.Keep(&ldquo;MyData&rdquo;);

The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well
advices MVC to maintain “TempData” for the subsequent request.

Hide   Copy Code

string str = TempData.Peek("Td").ToString();

If you want to read more in detail you can read from this detailed blog on MVC Peek and Keep.

What are partial views in MVC?


Partial view is a reusable view (like a user control) which can be embedded inside other view. For
example let’s say all your pages of your site have a standard structure with left menu, header, and
footer as shown in the image below.
Figure: Partial views in MVC

For every page you would like to reuse the left menu, header, and footer controls. So you can go and
create partial views for each of these items and then you call that partial view in the main view.

How did you create a partial view and consume


it?
When you add a view to your project you need to check the “Create partial view” check box.
Figure: Create partial view

Once the partial view is created you can then call the partial view in the main view using the
Html.RenderPartial method as shown in the below code snippet:
Hide   Copy Code

<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>

How can we do validations in MVC?


One of the easiest ways of doing validation in MVC is by using data annotations. Data annotations
are nothing but attributes which can be applied on model properties. For example, in the below code
snippet we have a simple Customer class with a property customercode.
This CustomerCode property is tagged with a Required data annotation attribute. In other words if
this model is not provided customer code, it will not accept it.
Hide   Copy Code

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 the ValidateMessageFor method


which belongs to the Html helper class.
Hide   Copy Code

<% 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
the ModelState.IsValid property and accordingly we can take actions.
Hide   Copy Code

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.

Figure: Validations in MVC

Can we display all errors in one go?


Yes, we can; use the ValidationSummary method from the Html helper class.
Hide   Copy Code

<%= Html.ValidationSummary() %>

What are the other data annotation attributes for validation in MVC?

If you want to check string length, you can use StringLength.


Hide   Copy Code

[StringLength(160)]
public string FirstName { get; set; }

In case you want to use a regular expression, you can use the RegularExpression attribute.
Hide   Copy Code

[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.
Hide   Copy Code

[Range(10,25)]public int Age { get; set; }

Sometimes you would like to compare the value of one field with another field, we can use
the Compare attribute.
Hide   Copy Code
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.
Hide   Copy Code

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.
Hide   Copy Code

TryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use the AddModelError function.
Hide   Copy Code

ModelState.AddModelError("FirstName", "This is my server-side error.");

How can we enable data annotation validation


on client side?
It’s a two-step process: first reference the necessary jQuery files.

Hide   Copy Code

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>

The second step is to call the EnableClientValidation method.


Hide   Copy Code

<% Html.EnableClientValidation(); %>

What is Razor in MVC?


It’s a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor was introduced
in MVC 3.

Why Razor when we already have ASPX?


Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in ASPX to
display simple time, we need to write:

Hide   Copy Code
<%=DateTime.Now%>

In Razor, it’s just one line of code:

Hide   Copy Code

@DateTime.Now

So which is a better fit, Razor or ASPX?


As per Microsoft, Razor is more preferred because it’s light weight and has simple syntaxes.

How can you do authentication and


authorization in MVC?
You can use Windows or Forms authentication for MVC.

How to implement Windows authentication for


MVC?
For Windows authentication you need to modify the web.config file and set the authentication mode
to Windows.
Hide   Copy Code

<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 that. Now only the
users specified in the controller and action can access it.
Hide   Copy Code

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}

How do you implement Forms authentication in


MVC?
Forms authentication is implemented the same way as in ASP.NET. The first step is to set the
authentication mode equal to Forms. The loginUrl points to a controller here rather than a page.
Hide   Copy Code

<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>

We also need to create a controller where we will check if the user is proper or not. If the user is
proper we will set the cookie value.

Hide   Copy Code

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 the Authorize attribute so that any unauthorized
user making a call to these controllers will be redirected to the controller (in this case the controller is
“Login”) which will do the authentication.
Hide   Copy Code

[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}
How to implement AJAX in MVC?
You can implement AJAX in two ways in MVC:

 AJAX libraries
 jQuery
Below is a simple sample of how to implement AJAX by using the “AJAX” helper library. In the below
code you can see we have a simple form which is created by using the Ajax.BeginForm syntax. This
form calls a controller action called getCustomer. So now the submit action click will be an
asynchronous AJAX call.
Hide   Copy Code

<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>

In case you want to make AJAX calls on hyperlink clicks, you can use the Ajax.ActionLink function
as shown in the below code.

Figure: Implement AJAX in MVC

So if you want to create an AJAX asynchronous hyperlink by name GetDate which calls


the GetDate function in the controller, below is the code for that. Once the controller responds, this
data is displayed in the HTML DIV tag named DateDiv.
Hide   Copy Code

<span id="DateDiv" />


<%:
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%>

Below is the controller code. You can see how the GetDate function has a pause of 10 seconds.
Hide   Copy Code
public class Default1Controller : Controller
{
public string GetDate()
{
Thread.Sleep(10000);
return DateTime.Now.ToString();
}
}

The second way of making an 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 into a function called GetData and you can make a call to the GetData function on a
button or a hyperlink click event as you want.
Hide   Copy Code

function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}

What kind of events can be tracked in AJAX?

Figure: Tracked in AJAX

What is the difference between ActionResult


and ViewResult?
 ActionResult is an abstract class while ViewResult derives from
the ActionResult class.ActionResult has several derived classes
like ViewResult, JsonResult, FileStreamResult, and so on.
 ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different
types of views dynamically, ActionResult is the best thing. For example in the below code snippet,
you can see we have a simple action called DynamicView. Depending on the flag (IsHtmlView) it will
either return aViewResult or JsonResult.
Hide   Copy Code

public ActionResult DynamicView()


{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}

What are the different types of results in MVC?


Note: It’s difficult to remember all the 12 types. But some important ones you can remember for the
interview areActionResult, ViewResult, and JsonResult. Below is a detailed list for your
interest:
There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class that can
have 11 subtypes as 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

What are ActionFilters in MVC?


ActionFilters help you to perform logic while an MVC action is executing or after an MVC action has
executed.
Figure: ActionFilters in MVC

Action filters are useful in the following scenarios:

1. Implement post-processing logic before the action happens.


2. Cancel a current execution.
3. Inspect the returned value.
4. Provide extra data to the action.

You can create action filters by two ways:

 Inline action filter.


 Creating an ActionFilter attribute.
To create an inline action attribute we need to implement the IActionFilter interface.
The IActionFilter interface has two methods: OnActionExecuted and OnActionExecuting.
We can implement pre-processing logic or cancellation logic in these methods.
Hide   Copy Code

public class Default1Controller : Controller , IActionFilter


{
public ActionResult Index(Customer obj)
{
return View(obj);
}
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action is executing");
}
}

The problem with the inline action attribute is that it cannot be reused across controllers. So we can
convert the inl ine action filter to an action filter attribute. To create an action filter attribute we need
to inherit fromActionFilterAttribute and implement the IActionFilter interface as shown in
the below code.
Hide   Copy 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 the MyActionAttribute class
which was created in the previous code.
Hide   Copy Code

[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}

What are the different types of action filters?


1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

If we have multiple filters, what’s the sequence


for execution?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
Can we create our custom view engine using
MVC?
Yes, we can create our own custom view engine in MVC. To create our own custom view engine we
need to follow three steps:

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 the 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 that.
Hide   Copy Code

public class MyCustomView : IView


{
private string _FolderPath; // Define where our views are stored
public string FolderPath
{
get { return _FolderPath; }
set { _FolderPath = value; }
}

public void Render(ViewContext viewContext, System.IO.TextWriter writer)


{
// Parsing logic <dateTime>
// read the view file
string strFileData = File.ReadAllText(_FolderPath);
// we need to and replace <datetime> datetime.now value
string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
// this replaced data has to sent for display
writer.Write(strFinal);
}
}

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”.
Hide   Copy Code

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
}
protected override IView CreateView(
ControllerContext controllerContext, string viewPath, string masterPath)
{
var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
MyCustomView obj = new MyCustomView(); // Custom view engine class
obj.FolderPath = physicalpath; // set the path where the views will be stored
return obj; // returned this view paresing
// logic so that it can be registered in the view engine collection
}
protected override IView CreatePartialView(ControllerContext controllerContext, string
partialPath)
{
var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
MyCustomView obj = new MyCustomView(); // Custom view engine class
obj.FolderPath = physicalpath; // set the path where the views will be stored
return obj;
// returned this view paresing logic
// so that it can be registered in the view engine collection
}
}

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 that.
Hide   Copy Code

protected void Application_Start()


{
// Step3 :- register this object in the view engine collection
ViewEngines.Engines.Add(new MyViewEngineProvider());
&hellip;..
}

Below is a simple output of the custom view written using the commands defined at the top.

Figure: Custom view engine using MVC

If you invoke this view, you should see the following output:
How to send result back in JSON format in MVC
In MVC, we have the JsonResult class by which we can return back data in JSON format. Below is a
simple sample code which returns back a Customer object in JSON format using JsonResult.
Hide   Copy Code

public JsonResult getCustomer()


{
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj.CustomerName = "Shiv";
return Json(obj,JsonRequestBehavior.AllowGet);
}

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 the past many years, browser was the most preferred client by
which we consumed data exposed over HTTP. But as years passed by, client variety started spreading
out. We had demand to consume data on HTTP from clients like mobile, JavaScript, Windows
applications, etc.

For satisfying the broad range of clients REST was the proposed approach. You can read more about
REST from the WCF chapter.

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?
SOAP WEB API

Heavy weight because of Light weight, only the necessary information is


Size
complicated WSDL structure. transferred.
SOAP WEB API

Protocol Independent of protocols. Only for HTTP protocol

To parse SOAP message, the


client needs to understand
WSDL format. Writing custom
code for parsing WSDL is a
Output of WebAPI are simple string messages, JSON,
heavy duty task. If your client
Formats simple XML format, etc. So writing parsing logic for that
is smart enough to create
is very easy.
proxy objects like how we
have in .NET (add reference)
then SOAP is easier to
consume and call.

SOAP follows WS-* WebAPI follows REST principles. (Please refer to REST in
Principles
specification. WCF chapter.)

With WCF you can implement REST, so why


WebAPI?
WCF was brought into implement SOA, the intention was never to implement REST. WebAPI is built
from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for
creating REST service, WebAPI is more preferred.

How to implement WebAPI in MVC

Below are the steps to implement WebAPI:

Step 1: Create the project using the WebAPI template.


Figure: Implement WebAPI in MVC

Step 2: Once you have created the project you will notice that the controller now inherits
from ApiController and you can now implement POST, GET, PUT, and DELETE methods of the
HTTP protocol.
Hide   Copy Code

public class ValuesController : ApiController


{
// 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 an HTTP GET call you should get the below results:
Figure: HTTP

How can we detect that an MVC controller is


called by POST or GET?
To detect if the call on the controller is a POST action or a GET action we can use
the Request.HttpMethodproperty as shown in the below code snippet.
Hide   Copy Code

public ActionResult SomeAction()


{
if (Request.HttpMethod == "POST")
{
return View("SomePage");
}
else
{
return View("SomeOtherPage");
}
}

What is bundling and minification in MVC?


Bundling and minification helps us improve request load times of a page thus increasing
performance.

How does bundling increase performance?


Web projects always need CSS and script files. Bundling helps us combine multiple JavaScript and
CSS files in to a single entity thus minimizing multiple requests in to a single request.
For example consider the below web request to a page . This page consumes two JavaScript
files Javascript1.js andJavascript2.js. So when this is page is requested it makes three request calls:
 One for the Index page.9*
 Two requests for the other two JavaScript files: Javascript1.js and Javascript2.js.

The below scenario can become worse if we have a lot of JavaScript files resulting in multiple
requests, thus decreasing performance. If we can somehow combine all the JS files into a single
bundle and request them as a single unit that would result in increased performance (see the next
figure which has a single request).

So how do we implement bundling in MVC?


Open BundleConfig.cs from the App_Start folder.
In BundleConfig.cs, add the JS files you want bundle into a single entity in to the bundles collection.
In the below code we are combining all the javascript JS files which exist in the Scripts folder as a
single unit in to the bundle collection.
Hide   Copy Code

bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));

Below is how your BundleConfig.cs file will look like:


Hide   Copy Code

public class BundleConfig


{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
BundleTable.EnableOptimizations = true;
}
}

Once you have combined your scripts into one single unit we then to include all the JS files into the
view using the below code. The below code needs to be put in the ASPX or Razor view.

Hide   Copy Code

<%= Scripts.Render("~/Scripts/MyScripts") %>

If you now see your page requests you would see that script request is combined into one request.

How can you test bundling in debug mode?


If you are in a debug mode you need to set EnableOptimizations to true in
the bundleconfig.cs file or else you will not see the bundling effect in the page requests.
Hide   Copy Code

BundleTable.EnableOptimizations = true;
Explain minification and how to implement it
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.

Hide   Copy Code

// This is test
var x = 0;
x = x + 1;
x = x * 2;

After implementing minification the JavaScript code looks like below. You can see how whitespaces
and comments are removed to minimize file size, thus increasing performance.

Hide   Copy Code

var x=0;x=x+1;x=x*2;

How do we implement minification?


When you implement bundling, minification is implemented by itself. In other words the steps to
implement bundling and minification are the same.

Explain Areas in MVC?


Areas help you to group functionalities in to independent modules thus making your project more
organized. For example in the below MVC project we have four controller classes and as time passes
by if more controller classes are added it will be difficult to manage. In bigger projects you will end
up with 100’s of controller classes making life hell for maintenance.

If we can group controller classes in to logical section like “Invoicing” and “Accounting” that would
make life easier and that’s what “Area” are meant to.
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 below 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.
 
Explain the concept of View Model in MVC?
A view model is a simple class which represents data to be displayed on the view.

For example below is a simple customermodel object with “CustomerName” and “Amount” property.

Hide   Copy Code

CustomerViewModel obj = new CustomerViewModel();


obj.Customer.CustomerName = "Shiv";
obj.Customer.Amount = 1000;

But when this “Customer” model object is displayed on the MVC view it looks something as shown in
the below figure. It has “CustomerName” , “Amount” plus “Customer Buying Level” fields on the
view / screen. “Customer buying Level” is a color indicationwhich indicates how aggressive the
customer is 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 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.

So the Customer viewmodel class has three properties

 “TxtCustomerName” textbox takes data from “CustomerName” property as it is.


 “TxtAmount” textbox takes data from “Amount” property of model as it is.
 “CustomerBuyingLevelColor” displays color value depending on the “Amount “ value.
Customer Model Customer ViewModel

CustomerName TxtCustomerName

Amount TxtAmount

CustomerBuyingLevelColor

What kind of logic view model class will have?


As the name says view model this class has the gel code or connection code which connects the view
and the model.

So the view model class can have following kind of logics:-

 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”.
 Aggregation logic: -You have two differentCustomer and Address model classes and you have view
which displays both “Customer” and “Address” data on one go.
 Structure downsizing: - 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.
How can we use two ( multiple) models with a
single view?
Let us first try to understand what the interviewer is asking. When we bind a model with a view we
use the model dropdown as shown in the below figure. In the below figure we can only select one
model.

But what if we want to bind “Customer” as well as “Order” class to the view.
For that we need to create a view model which aggregates both the classes as shown in the below
code. And then bind that view model with the view.
Hide   Copy Code

public class CustOrderVM


{
public Customer cust = new Customer();
public Order Ord = new Order();
}

In the view we can refer both the model using the view model as shown in the below code.
Hide   Copy Code

<%= model.cust.Name %>


<%= model.Ord.Number %>

Explain the need of display mode in MVC?


Display mode displays views depending on the device the user has logged in with. So we can create
different views for different devices anddisplay mode will handle the rest.
For example we can create a view “Home.aspx” which will render for the desktop computers
andHome.Mobile.aspx for mobile devices. Now when an end user sends a request to the MVC
application, display mode checks the “user agent” headers and renders the appropriate view to the
device accordingly.

Explain MVC model binders?


Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and
MVC model. Many times HTML UI names are different than the model property names. So in the
binder we can write the mapping logic between the UI and the model.
Explain the concept of MVC Scaffolding?
Hide   Copy Code

Note :- Do not get scared with the word. Its actually a very simple thing.

Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD
stands for create, read, update and delete.

So to generate code using scaffolding technique we need to select one of the types of templates
(leave the empty one).

For instance if you choose “using Entity framework” template the following code is generated.
It creates controller code, view and also table structure as shown in the below figure.

What does scaffolding use internally to connect


to database?
It uses Entity framework internally.

How can we do exception handling in MVC?


In the controller you can override the “OnException” event and set the “Result” to the view name
which you want to invoke when er+ror occurs. In the below code you can see we have set the
“Result” to a view named as “Error”.

We have also set the exception so that it can be displayed inside the view.

Hide   Copy Code
public class HomeController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;

var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");

filterContext.Result = new ViewResult()


{
ViewName = "Error",
ViewData = new ViewDataDictionary(model)
};

}
}

To display the above error in view we can use the below code

Hide   Copy Code

@Model.Exception;

How can you handle multiple Submit buttons


pointing to multiple actions in a single MVC
view?
Let us elaborate on what the interviewer wants to ask because the above question is just a single
liner and is not clear about what the interviewer wants.

Take a scenario where you have a view with two submit buttons as shown in the below code.

Hide   Copy Code

<form action="Action1" method=post>


<input type=&rdquo;submit&rdquo; name=&rdquo;Submit1&rdquo;/>
<input type=&rdquo;submit&rdquo; name=&rdquo;Submit2&rdquo;>
</form>

In the above code when the end user clicks on any of the submit buttons it will make a HTTP POST to
“Action1”.

The question from the interviewer is:-


“What if we have want that on “Submit1” button click it should invoke “Action1” and on the “Submit2”
button click it should invoke “Action2”.”

Now that we have understood the question let us answer the question in a detailed manner. There
are two approaches to solve the above problem one is the normal HTML way and the other is the
“Ajax” way.

In the HTML way we need to create two forms and place the “Submit” button inside each of the
forms. And every form’s action will point to different / respective actions. You can see the below
code the first form is posting to “Action1” and the second form will post to “Action2” depending on
which “Submit” button is clicked.

Hide   Copy Code

<form action="Action1" method=post>


<input type=&rdquo;submit&rdquo; name=&rdquo;Submit1&rdquo;/>
</form>

In case the interviewer complains that the above approach is not AJAX this is where the second
approach comes in. In the Ajax way we can create two different functions “Fun1” and “Fun1” , see the
below code. These function will make Ajax calls by using JQUERY or any other framework. Each of
these functions are binded with the “Submit” button’s “OnClick” events.

Hide   Copy Code

<Script language="javascript">
function Fun1()
{
$.post(&ldquo;/Action1&rdquo;,null,CallBack1);
}
function Fun2()
{
$.post(&ldquo;/Action2&rdquo;,null,CallBack2);
}
</Script>

What is CSRF attack and how can we prevent


the same in MVC?
CSRF stands for Cross site request forgery. So if you see the dictonary meaning of forgery: -

“It’s an act of copying or imitating things like signature on a cheque, official documents to deceive the
authority source for financial gains.”

So when it comes to website this forgery is termed as CSRF (Cross Site Request Forgery).
CSRF is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source
and sends data to the site. Genuine site processes the information innocently thinking that data is
coming from a trusted source.

For example conside the below screen of a online bank. End user’s uses this screen to transfer
money.

Below is a forged site created by an attacker which looks a game site from outside, but internally it
hits the bank site for money transfer.

The internal HTML of the forged site has those hidden fields which have the account number and
amount to do money transfer.

Hide   Copy Code

<div>
Win 1000000 US$
<form action="http://localhost:23936/Genuine/Transfer" method=post>
<input type=hidden name="amount" value="10000" />
<input type=hidden name="account" value="3002" />
<input type=submit value="Play the ultimate game" />
</form>
</div>

Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game
link to his email. The end user thinking that it’s a game site clicks on the “Play the Ultimate Game”
button and internally the malicious code does the money transfer process.
So a proper solution to this issue can be solved by using tokens: -

o End user browses to the screen of the money transfer. Before the screen is served server injects a
secret token inside the HTML screen in form a hidden field.
o Now hence forth when the end user sends request back he has to always send the secret token. This
token is validated on the server.

Implementing token is a two-step process in MVC: -


First apply “ValidateAntiForgeryToken” attribute on the action.

Hide   Copy Code

[ValidateAntiForgeryToken]
public ActionResult Transfer()
{
// password sending logic will be here
return Content(Request.Form["amount"] +
" has been transferred to account "
+ Request.Form["account"]);
}

Second in the HTML UI screen call “@Html.AntiForgeryToken()” to generate the token.

Hide   Copy Code

<div>
Transfer money
<form action="Transfer" method=post>
Enter Amount
<input type="text" name="amount" value="" />

Enter Account number

@Html.AntiForgeryToken()
<input type=submit value="transfer money" />
</form>
</div>

So now henceforth when any untrusted source send a request to the server it would give the below
forgery error.

If you do a view source of the HTML you would find the below verification token hidden field with
the secret key.

Hide   Copy Code
<input name="__RequestVerificationToken" type="hidden"
value="7iUdhsDNpEwiZFTYrH5kp/q7jL0sZz+CSBh8mb2ebwvxMJ3eYmUZXp+uofko6eiPD0fmC7Q0o4SXeGgRpxFp0i+
Hx3fgVlVybgCYpyhFw5IRyYhNqi9KyH0se0hBPRu/9kYwEXXnVGB9ggdXCVPcIud/gUzjWVCvU1QxGA9dKPA=" />

Learn MVC Project in 7 days – Day 1


ASP.NET vs MVC vs WebForms
“You are reading this article because you know ASP.NET and you want to upgrade yourself to MVC.”

Sorry for the trouble, can you please read the above statement again and if you think it’s right then
this section is a must read for you.

Lot of ASP.NET developers who start MVC for the first time think that MVC is different new , fresh
from ASP.NET. But the truth is ASP.NET is a framework for creating web application while MVC is a
great architecture to organize and arrange our code in a better way. So rather than MVC you can say
ASP.NET MVC.

Ok so if the new thing is ASP.NET MVC what is the old thing called as,it’s “ASP.NET Webforms”.

Let me correct your vocabulary:-

“You are reading this article because you know ASP.NET Webforms and you want to upgrade yourself
to ASP.NET MVC.”

So now that your vocabulary is corrected welcome to the world of ASP.NET MVC and let’s start this
tutorial.

Why ASP.NET Web Forms?


ASP.NET Webforms has served and successfully delivered web application for past 12 years.Let us try
to understand the secret of what made Webform’s so popular and successful.

If you see the success of Microsoft programming languages right from the days of VB (visual basic) it
is due to RAD(Rapid application development)and visual programming approach.Visual
programming was so much preached and successful in Microsoft that literally they named their IDE’s
as “Visual studio”.
By using visual studio ,developers where able to drag drop UI elements on a designer area and at the
backend , visual studio generates C# or VB.NET code for those elements. These codes where termed
as “Behind Code” or “Code Behind”. In this code behind Developers can go and write logic to
manipulate the UI elements.

So the visual RAD architecture of Microsoft has two things one is the UI and the other is the code
behind. So for ASP.NET Web forms you have ASPX and ASPX.CS ,for WPF you have XAML / XAML.CS
and so on.

Problems with Asp.Net Web Forms


So when ASP.NET Webform was so successful, why Microsoft thought of creating ASP.NET MVC.The
main problem with ASP.NET Webform is performance, performance and performance. In web
application there are two aspects which define performance:-

1. Response time: - How fast the server responds to request?.


2. Bandwidth consumption: - How much data is sent ?.
Response time issues

Let us try to understand why response time is slower when it comes to ASP.NET Webforms. We did a
small load testing experiment of Webform vs Asp.Net MVC and we found Asp.Net MVC to be twice
faster.
Read more on how this test was done from here

Let us try to understand why ASP.NET MVC was better in performance in the above load
test.Consider the below simple UI code and Code behind for that UI.

Assume the ASPX code has the below simple text box.

Hide   Copy Code

<asp:TextBox ID="TextBox1" runat="server">

In the code behind you have written some logic which manipulates the text box values and the back
ground color.

Hide   Copy Code

protected void Page_Load(object sender, EventArgs e)


{
TextBox1.Text = "Make it simple";
TextBox1.BackColor = Color.Aqua;
}

When you run the above program below is the HTML output.

If you see the HTML output by doing view source it looks something as shown below.

Hide   Copy Code

<input name="TextBox1" type="text" value="Make it simple" id="TextBox1" style="background-


color:Aqua;" />
Now stop reading for a moment, close your eyes and think. Try to get answers to the below
questions:-

1. Is this a efficient way of generating HTML?. Do we really need to make those long server trips to get
those simple HTML on the browser ?.
2. Can’t the developer write HTML straight forward , Is it so tough?

If you see for every request there is a conversion logic which runs and converts the server controls to
HTML output.This conversion get’s worse and heavy when we have grids, tree view controls etc
where the HTML outputs are complicated HTML tables. Due to this unnecessary conversion the
response time get affected.

Solution for this problem: - “GET RID of CODE BEHIND” ,fold your sleeves and work with pure HTML.

Bandwidth consumption
Viewstate has been a very dear and near friend of ASP.NET developers for past 10 years because it
automatically saves states between post backs and reduces our development time. But this reduction
in development time comes at a huge cost ,viewstate increases the page size considerably. In
this load test we found viewstate increases the page size twice as compared to Asp.Net MVC.

Below is the plot of the content length emitted from Webform and Asp.Net MVC.

The size increase is because of extra bytes generated from viewstate , below is the snapshot of a
viewstate. Lot of people can argue that viewstate can be disabled but then we all know how
developers are , if there is option given they would definitely try that out.
Solution for this problem: - “GET RID of SERVER CONTROLS”.

Note: -The rest of the three points down below are browny issues which have cropped up due to
presence of code behind and server controls. But the main thing is always performance.

HTML customization

Now because we are salves of the code behind and ASP.NET web server controls, we have “NO IDEA”
what kind of HTML can come out and how efficient they are. For example see the below ASPX code,
can you guess what kind of HTML it will generate.

Hide   Copy Code

<asp:Label ID="Label1" runat="server" Text="I am label">


<asp:Literal ID="Literal1" runat="server" Text="I am a literal">
<asp:Panel ID="Panel1" runat="server">I am a panel

Will Label generate DIV tag or SPAN tag ?. If you run the above code below are the respective
generated HTML. Label generates a SPAN , Literal generates simple text , Panel generates DIV tag
and so on.

Hide   Copy Code

<span id="Label1">I am label</span>


I am a literal

I am a panel

So rather than generating HTML using server controls how about writing HTML directly and taking
complete control of HTML.

So the solution for this problem is “DO NOT USE SERVER CONTROLS” and work with direct HTML.
The other great benefit of working directly with HTML is that your web designers can work very
closely with the developer team. They can take the HTML code put in their favourite designer tool
like dream weaver , front page etc and design independently . If we have server controls these
designer tools do not identify them easily.

Reusability of code behind class

If you watch any professional ASP.NET Webform project you will notice that code behind class is
where you have huge amount of code and the code is really complicated.Now this code behind page
class inherits from “System.Web.UI.Page” class. This class is not a normal class which can be reused
and instantiated anywhere. In other words you can never do something as shown below for a
Webform class:-

Hide   Copy Code

WebForm1 obj = new WebForm1();


obj.Button1_Click();

Because the “WebForm” class cannot instantiate with out “request” and “response” object. If you
have ever seen the “ButtonClick” events of “WebForm” they are as shown in the code below. From
the code you can know how difficult it is to instantiate the same.

Hide   Copy Code

protected void Button1_Click(object sender, EventArgs e)


{
// The logic which you want to reuse and invoke
}

Solution for this problem: - “GET RID of SERVER CONTROLS and CODE BEHIND”.

Unit Testing

As said in the previous section you cannot instantiate behind code straight forward it’s very difficult
to do unit testing or I will say automation testing on the code behind. Someone has to manually run
the application and do the testing.

What’s the solution ?


If we read the four issues mentioned in the previous section with ASP.NET Webforms the main culprit
are two people “Code Behind” and “Server controls”. Below is root cause diagram I have drawn. In
this I started with problems , what is the cause for it and the solution for the same. The complete
diagram zeroes on two things “Code Behind” and “Server controls”.
The solution is we need to move the code behind to a separate simple class library and get rid of
ASP.NET Server controls and write simple HTML.

In short the solution should look something as shown in the below image.

How Microsoft Asp.Net MVC tackles problems


in Web Forms?
As said the code behind and server controls are the root cause problem. So if you look at the current
WebForm architecture which developers are using it’s mostly 3 layer architecture. This three layer
architecture comprises of UI which has ASPX and the CS code behind.

This UI talk’s with .NET classes which you can term as middle layer , business logic etc and the middle
layer talks with data access layer.
So Asp.Net MVC comprises of three sections Model , View and Controller. The code behind logic
goes in to the controller. View is your ASPX i.e. pure HTML and your Model is your middle layer. You
can see in the above diagram how those layers fit in.

So if you see there are two major changes VIEW becoming simple HTML and code behind moving to
simple .NET classes termed as controller.

In Asp.Net MVC request flow in general moves as follows:-

Step 1:- The first hit comes to the controller.

Step 2:- Depending on the action controller creates the object of the model. Model in turn calls the
data access layer which fetches data in the model.

Step 3:- This data filled model is then passed to the view for display purpose.

Now that we have understood the different components of Asp.Net MVC let’s go in depth in to each
one of these components , let us start doing some lab’s. Let us first start with controllers as they are
the most important and central part of the MVC architecture.

Understand Controller in Asp.Net MVC?


In order to understand Controller first we need to understand this term User interaction logic.
What is User Interaction logic??
Scenario 1

Did you ever gave a thought what happen’s, when end user hits a URL on a browser.

Browser sends request to server and server sends a response.

By means of such request, client is trying to interact with server. Server is able to respond back
because some logic is written at server end to fulfil this request.

Some logic??, So what exactly can be this logic ?.

Logic which will handle the user requests and user’s interaction with server. In short User Interaction
Logic

Scenario 2

It also possible that response sent by Server is an HTML response. HTML response which can consist
of couple of input controls and a submit button.

What will happen when “Save Customer” button is clicked?


If your answer is “Some event handler will handle the button click”, then sorry   .

“In reality in web programming there is no concept of event’s. In case of Asp.net Web Forms Microsoft
wrote some code on behalf of us and brought us the feeling of event driven programming. It’s just an
abstraction or the right word would illusion.”

When button is clicked a simple HTTP request is sent to the server. This time the difference is, values
in the “Customer Name”, “Address” and “Age” will be sent along with request. (In technical terms
“values are posted to the server”). Ultimately, if it’s a request then there must be a logic written in the
server so that server can send back the response. In short there must be some user interaction logic
written on the server.

In Asp.Net MVC, the last letter C that is Controller is the one who will handle the user interaction
Logic.

Lab 1 – Demonstrating Controller with a simple


MVC hello world
Step 1 – Create Asp.Net MVC 5 Project

Step 1.1 Open Visual studio 2013(or higher). Click on File>>New>>Project.

Step 1.2 Select Web Application. Put Name. Put Location and say ok.
Step 1.3 Select MVC template

Step 1.4 Click on Change Authentication. Select “No Authentication” from “Change Authentication”
dialog box and click ok.
Step 1.5. Click ok.

Step 2 – Create Controller

Step 2.1. In the solution explorer, right click the controller folder and select Add>>Controller

Step 2.2. Select “MVC 5 Controller – Empty” and click Add


Step 2.3.Put controller name as “TestController” and click Add.

One very important point to note at this step is do not delete the word controller. For now you can
think it’s like a reserved keyword.

Step 3. Create Action Method

Open newly created TestController class. You will find a method inside it called “Index”. Remove that
method and add new public method called “GetString” as follows.

Hide   Copy Code

public class TestController : Controller


{
public string GetString()
{
return "Hello World is old now. It&rsquo;s time for wassup bro ;)";
}
}

Step 4. Execute and Test

Press F5. In the address bar put “ControllerName/ActionName” as follows. Please note do not type
the word “Controller” just type “Test”.
Q & A session around Lab 1
What is the relationship between TestController and Test?

TestController is the class name whereas Test is the controller name. Please note, when you type the
controller name on the URL it should be without the word controller.

Asp.Net MVC follows Convention based approach. It strictly look’s into the conventions we used.

In Asp.Net MVC two things are very important.

1. How we name something?


2. Where we keep something?
What is Action Method?

Action method is simply a public method inside controller which accepts user’s request and returns
some response. In above example, action method “GetString” is returning a string response type.

Note: In Asp.Net Web Forms default return response is always HTML. In case we want to return
something other than HTML (in asp.net Web Forms), we create HTTP handlers, override content
type , do response.end etc. It’s not an easy task. In Asp.net MVC it’s very easy. If return type is ‘string’
you can just return string   , you do not need to send complete HTML.

What will happen if we try to return an object from an action method?

Look at the following code block.

Hide   Copy Code

namespace WebApplication1.Controllers
{
public class Customer
{
public string CustomerName { get; set; }
public string Address { get; set; }
}
public class TestController : Controller
{
public Customer GetCustomer()
{
Customer c = new Customer();
c.CustomerName = "Customer 1";
c.Address = "Address1";
return c;
}
}
}

Output of above action method will look as shown below.

When return type is some object like ‘customer’, it will return ‘ToString()’ implementation of that
object.By default ‘ToString()’ method returns fully qualified name of the class which is
“NameSpace.ClassName”;

What if you want to get values of properties in above example?

Simply override “ToString” method of class as follows.

Hide   Copy Code

public override string ToString()


{
return this.CustomerName+"|"+this.Address;
}

Press F5. Output will be as follows.

Is it must to decorate action methods with public access modifier?

Yes, every public method will become action methods automatically.

What about non-public methods?

They are simply methods of a class and not available publicly . In simple words these methods can
not be invoked from the web.
What if we want a method to be public but not action method?

Simply decorate it with NonAction attribute as follows.

Hide   Copy Code

[NonAction]
public string SimpleMethod()
{
return "Hi, I am not action method";
}

When we try to make request to above action method we will get following response.

Understand Views in Asp.Net MVC


As we discussed earlier controller will handle the user’s requests and send the response. Most
commonly the response is HTML as browser understands that format much better. HTML with some
images, texts, Input controls etc. Normally in technical world layer defining the user interface design
is termed as UI layer and in Asp.Net MVC it is termed as View.

Lab 2 – Demonstrating Views


In the first lab we created a simple MVC application with just controller and simple string return type.
Let us go add view part to the MVC application.

Step 1 – Create new action method

Add a new action method inside TestController as follows.

Hide   Copy Code

public ActionResult GetView()


{
return View("MyView");
}

Step 2 – Create View

Step 2.1. Right click the above action method and select “Add View”.

Step 2.2. In the “Add View” dialog box put view name as “MyView”, uncheck “use a layout” checkbox
and click “Add”.

It will add a new view inside “Views/Test” folder in solution explored


Step 3 – Add contents to View

Open MyView.cshtml file and add contents as follows.

@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MyView</title>
</head>
<body>

Welcome to MVC 5 Step by Step learning

</body> </html>

Step 3. Test and Execute

Press F5 and execute the application.

Q and A session around Lab 2


Why View is placed inside Test Folder?
In ASP.net MVC, Views associated with the particular controller is placed inside a special folder. This
special folder will be named as “ControllerName” and placed inside Views folder (located in the root
folder). For every controller only those views will be available which are located inside its own folder.

For example: All the views related to Test controller will be placed inside “~/Views/Test” and Test
controller can access only those views which are inside Test folder.

Can’t we reuse some of the views across multiple controllers?

Yes, we can. For that we will keep those files inside a special folder called “Shared”.

Views located inside this Shared folder will be available to all the controllers.

Is it possible that one action method is referencing more than one views?

Yes. Look at the following code.

Hide   Copy Code

public ActionResult GetView()


{
if(Some_Condition_Is_Matching)
{
return View("MyView");
}
else
{
return View("YourView");
}
}

Note: In Asp.Net MVC views and controllers are not tightly coupled. One action method can refer
more than one view and one view can be referred by more than one action method (by keeping
them in Shared folder). It provides better reusability

What is the purpose of View function?

Creates ViewResult object which renders View to the response.


 ViewResult internally creates the object of ViewPageActivator
 ViewResult choose the correct ViewEngine and passes ViewPageActivator object as argument to
ViewEngine’s constructor.
 ViewEngine create the object of View class
 ViewResult invoke the RenderView method of View.

Note: We have separate topic in the series disucssing Asp.Net MVC life cycle in detail.

What is the relation between ActionResult and ViewResult?

ActionResult is the abstract class whereas ViewResult is the multi level child of ActionResult.
Multilevel because, ViewResult is the child of ViewResultBase and ViewResultBase is the child of
ActionResult.

If we want to return ViewResult why ActionResult is the ViewResult?

To achieve polymorphism. Look at the following example.

Hide   Copy Code

public ActionResult GetView()


{
if(Some_Condition_Is_Matching)
{
return View("MyView");
}
else
{
return Content("Hi Welcome");
}
}

In the above example, when some condition is matching we are returning we are invoking “View”
function which will return ViewResult whereas in some other condition we are invoking “Content”
function which is returning Content Result.

What is ContentResult?

ViewResult represents a complete HTML response whereas ContentResult represents a scalar text
response. It’s just like returning pure string. Difference is ContentResult is a ActionResult wrapper
around string result. ContentResult is also the child of ActionResult.

Is it possible to invoke View function without Parameter?

Yes, then it will find the view with name “CurrentActionName”.


Learn MVC Project in 7 days – Day 2
Passing Data from Controller to View
View created in the Lab 2 is very much static. In real life scenario it will display some dynamic data. In
the next lab we will display some dynamic data in the view.

View will get data from the controller in the form of Model.

Model

In Asp.Net MVC model represent the business data.

Lab 3 – Using ViewData


ViewData is a dictionary, which will contains data to be passed between controller and views.
Controller will add items to this dictionary and view reads from it. Let’s do a demo.

Step 1 - Create Model class

Create a new class Called Employee inside Model folder as follows.

Hide   Copy Code

public class Employee


{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Salary { get; set; }
}

Step 2 -Get Model in controller

Create Employee object inside GetView method as follows

Hide   Copy Code

Employee emp = new Employee();


emp.FirstName = "Sukesh";
emp.LastName="Marla";
emp.Salary = 20000;

Note: Make sure to put using statement in the top or else we have to put fully qualified name of
Employee class.
Hide   Copy Code
using WebApplication1.Models;

Step 3 – Create ViewData and return View

Store Employee object in viewdata as follows.

Hide   Copy Code

ViewData["Employee"] = emp;
return View("MyView");

Step 4 - Display Employee Data in View

Open MyView.cshtml.

Retrieve the Employee data from the ViewData and display it as follows.

Hide   Copy Code

<div>
@{
WebApplication1.Models.Employee emp=(WebApplication1.Models.Employee)
ViewData["Employee"];
}

<b>Employee Details </b><br />


Employee Name : @emp.FirstName@emp.LastName <br />
Employee Salary: @emp.Salary.ToString("C")
</div>

Step 5- Test the out

put

Press F5 and test the application.


Talk on Lab 3
What is the difference between writing Razor code with brace brackets (that is “{“ and “}”) and
without brace brackets?

In the last lab @emp.FirstName can be replaced with following code snippet.

Hide   Copy Code

@{
Response.Write(emp.FirstName);
}

@ Without brace brackets simply display the value of variable or expression.

Why casting is required?

ViewData holds objects internally. Every time a new value is added into it, it get boxed to object type.

So unboxing is required every time we try to extract value out of it.

What is the meaning of “@emp.FirstName @emp.LastName”?

It means Display First Name followed by a space and then last name.

Can we write same thing with single @ keyword?

Yes, then syntax for this will be @(emp.FirstName+” “+emp.LastName)

Why hardcoded Employee class is created in Controller?

Just for demo purpose. In real time we will get it from may be database or wcf or web service or may
be from somewhere else.

What about the Database Logic/ Data Access Layer and Business Layer?

 Data Access Layer is one of the unspoken layer in Asp.Net MVC. It’s always there but never included
in MVC definition.
 Business layer as explained prior, it’s a part of Model.

Complete MVC structure


Lab 4 – Using ViewBag
ViewBag is just a syntactic sugar for ViewData. ViewBag uses the dynamic feature of C# 4.0 and
makes ViewData dynamic.

ViewBag internally uses ViewData.

Step 1 – Create View Bag

Continue with the same Lab 3 and replace Step 3 with following code snippet.

Hide   Copy Code

ViewBag.Employee = emp;

Step 2 - Display EmployeeData in View

Change Step 4 with following code snippet.

Hide   Copy Code

@{
WebApplication1.Models.Employee emp = (WebApplication1.Models.Employee)
ViewBag.Employee;
}
Employee Details

Employee Name: @emp.FirstName @emp.LastName

Employee Salary: @emp.Salary.ToString("C")

Step 3 - Test the output

Press F5 and test the application


Talk on Lab 4
Can we pass ViewData and get it as ViewBag?

Yes, We can. Vice versa is also possible. As I said before, ViewBag is just a syntactic sugar for
ViewData,

Problems with ViewData and ViewBag


ViewData and ViewBag is a good option for passing values between Controller and View. But in real
time projects it’s not a good practice to use any of them. Let’s discuss couple of disadvantages of
using ViewData and ViewBag.

Performance issues

Values inside the ViewData are of type Object. We have to cast the value to correct type before using
it. It adds additional overhead on performance.

No Type safety and no compile time errors

If we try to cast values to wrong type or if we use wrong keys while retrieving the values, we will get
runtime error. As a good programming practice, error should be tackled in compiled time.

No Proper connection between Data sent and Data Received

As a developer I personally found this as a major issue.

In MVC, controller and View are loosely connected to each other. Controller is completely unaware
about what’s happening in View and View is unaware about what’s happening in Controller.

From Controller we can pass one or more ViewData/ViewBag values. Now when Developer writes a
View, he/she have to remember what is coming from the controller. If Controller developer is
different from View developer then it becomes even more difficult. Complete unawareness. It leads
to many run time issues and inefficiency in development.
Lab 5 - Understand strongly typed Views
Reason for all three problems of ViewData and ViewBag is the data type. Data type of values inside
ViewData, which is “Object”.

Somehow if we were able to set the type of data which need to be passed between Controller and
View problem will get solved and that’s where strongly typed Views comes to picture.

Let’s do a demo. This time we will take our View requirement to next level. If salary is greater than
15000 then it will be displayed in yellow colour or else green colour.

Step 1 – Make View a strongly typed view

Add following statement in the top of the View

Hide   Copy Code

@model WebApplication1.Models.Employee

Above statement make our View a strongly typed view of type Employee.

Step 2 – Display Data

Now inside View simply type @Model and Dot (.) and in intellisense you will get all the properties of
Model (Employee) class.

Write down following code to display the data

Hide   Copy Code

Employee Details

Employee Name : @Model.FirstName @Model.LastName

@if(Model.Salary>15000)
{
<span style="background-color:yellow">
Employee Salary: @Model.Salary.ToString("C")
</span>
}
else
{
<span style="background-color:green">

Employee Salary: @Model.Salary.ToString("C")


</span>
}

Step 3 – Pass Model data from Controller Action method

Change the code in the action method to following.

Hide   Copy Code

Employee emp = new Employee();


emp.FirstName = "Sukesh";
emp.LastName="Marla";
emp.Salary = 20000;
return View("MyView",emp);

Step 4 – Test the output

Talk on Lab 5
Is it required to type fully qualified class Name (Namespace.ClassName) in View every time?

No, we can put a using statement.

Hide   Copy Code

@using WebApplication1.Models
@model Employee

Is it must to make View a strongly typed view always or can we go with ViewData or ViewBag
sometimes?

As a best practice always make the view a strongly typed view.

Can we make our View a strongly typed view of more than one model?

No, we can’t. In real time project we often end up at a point where we want to display multiple
models in same view. Solution for this requirement will be discussed in next lab.
Understand View Model in Asp.Net MVC
In Lab 5 we have violated MVC principle. According to MVC, V that is View should be pure UI. It
should not contain any kind of logic. We have done following three things which purely violates MVC
architecture rules.

 Append First name and Last Name and Display it as Full Name - Logic
 Display Salary with Currency – Logic
 Display Salary in different colour based on value. In simple words Change appearance of HTML
element based on some value. – Logic

Other than these three issues, there isone more pointworth discussion.
Let say we have situation where we want to display more than one kind of data in the View.
Example – Show Current logged in User’s Name along with Employee data

We can implement this in one of the following ways.

1. Add UserName property to Employee class –Every time we want to display new data in the view,
adding new property to Employee class seems illogical. This new property may or may not be related
to Employee. It also violates SRP of SOLID principle.
2. Use ViewBag or ViewData – We already discussed problems of using this approach.

ViewModel a solution
ViewModel is one of the unspoken layer in the Asp.Net MVC application. It fits between Model and
View and act as data container for View

Difference between Model and ViewModel?

Model is Business specific data. It will be created based on Business and Database structure.
ViewModel is View specific data. It will be created based on the View.

How it works exactly?

It’s simple.

 Controller handle the user interaction logic or in simple words, handles the user’s requests.
 Controller get one or more model data.
 Controller will decide which View suits best as response for the correct request.
 Controller will create and initialize ViewModel object from Model data retrieved based on View
Requirement
 Controller will pass ViewModel data to View by means of ViewData/ViewBag/Stongly typed View.
 Controller will return the view.
How View and ViewModel will be connected here?

View is going to be a strongly typed view of type ViewModel.

How Model and ViewModel will be connected?

Model and ViewModel should be independent of each other. Controller will create and initialises
ViewModel object based on one or more Model object.

Let’s do a small lab to understand it better.

Lab 6 – Implementing View Model


Step 1 – Create Folder

Create a new folder called ViewModels in the project

Step 2 – Create EmployeeViewModel

In order to do that, let’s list all the requirement on the view

1. First Name and Last Name should be appended before displaying


2. Amount should be displayed with currency
3. Salary should be displayed in different colour (based on value)
4. Current User Name should also be displayed in the view as well

Create a new class called EmployeeViewModel inside ViewModels folder will looks like below.

Hide   Copy Code

public class EmployeeViewModel


{
public string EmployeeName { get; set; }
public string Salary { get; set; }
public string SalaryColor { get; set; }
public string UserName{get;set;}
}

Please note, in View Model class, FirstName and LastName properties are replaced with one single
property called EmployeeName, Data type of Salary property is string and two new
propertiesareadded called SalaryColor and UserName.

Step 3 – Use View Model in View

In Lab 5 we had made our View a strongly type view of type Employee. Change it to
EmployeeViewModel
Hide   Copy Code

@using WebApplication1.ViewModels
@model EmployeeViewModel

Step 4 – Display Data in the View

Replace the contents in View section with following snippet.

Hide   Copy Code

Hello @Model.UserName
<hr />
<div>
<b>Employee Details</b><br />
Employee Name : @Model.EmployeeName <br />
<span style="background-color:@Model.SalaryColor">
Employee Salary: @Model.Salary
</span>
</div>

Step 5 – Create and Pass ViewModel

In GetView action method,get the model data and convert it to ViewModel object as follows.

Hide   Copy Code

public ActionResult GetView()


{
Employee emp = new Employee();
emp.FirstName = "Sukesh";
emp.LastName="Marla";
emp.Salary = 20000;

EmployeeViewModel vmEmp = new EmployeeViewModel();


vmEmp.EmployeeName = emp.FirstName + " " + emp.LastName;
vmEmp.Salary = emp.Salary.ToString("C");
if(emp.Salary>15000)
{
vmEmp.SalaryColor="yellow";
}
else
{
vmEmp.SalaryColor = "green";
}

vmEmp.UserName = "Admin"

return View("MyView", vmEmp);


}

Step 5 – Test the output

Press F5 and Test the output


Same output as Lab 5 but this time View won’t contain any logic.

Talk on Lab 6
Does it means, every model will have one View Model?

No, Every View will have its corresponding ViewModel.

Is it a good practice to have some relationship between Model and ViewModel?

No, as a best practice Model and ViewModel should be independent to each other.

Should we always create ViewModel? What if View won’t contain any presentation logic and it
want to display Model data as it is?

We should always create ViewModel. Every view should always have its own ViewModel even if
ViewModel is going to contain same properties as model.

Let’s say we have a situation where View won’t contain presentation logic and it want to display
Model data as it is.Let’s assume we won’t create a ViewModelin this situation.
Problem will be, if in future requirement,ifwe have been asked to show some new data in our UI or if
we asked to put some presentation logic we may end with complete new UI creation from the
scratch.
So better if we keep a provision from the beginning and Create ViewModel. In this case, in the initial
stage ViewModel will be almost same as Model.

Lab 7– View With collection


In this lab we will display list of Employees in the View.

Step 1 – Change EmployeeViewModel class

Remove UserName property from EmployeeViewModel.

Hide   Copy Code
public class EmployeeViewModel
{
public string EmployeeName { get; set; }
public string Salary { get; set; }
public string SalaryColor { get; set; }
}

Step 2– Create Collection View Model

Create a class called EmployeeListViewModel inside ViewModel folder as follows.

Hide   Copy Code

public class EmployeeListViewModel


{
public List<EmployeeViewModel><employeeviewmodel> Employees { get; set; }
public string UserName { get; set; }
}
</employeeviewmodel>

Step 3 – Change type of strongly typed view

Make MyView.cshtml a strongly typed view of type EmployeeListViewModel.

Hide   Copy Code

@using WebApplication1.ViewModels
@model EmployeeListViewModel

Step 4– Display all employees in the view

Hide   Copy Code

<body>
Hello @Model.UserName
<hr />
<div>
<table>
<tr>
<th>Employee Name</th>
<th>Salary</th>
</tr>
@foreach (EmployeeViewModel item in Model.Employees)
{
<tr>
<td>@item.EmployeeName</td>
<td style="background-color:@item.SalaryColor">@item.Salary</td>
</tr>
}
</table>
</div>
</body>
Step 5 – Create Business Layer for Employee

In this lab, we will take our project to next level. We will add Business Layer to our project. Create a
new class called EmployeeBusinessLayer inside Model folder with a method called GetEmployees.

Hide   Copy Code

public class EmployeeBusinessLayer


{
public List<Employee><employee> GetEmployees()
{
List<Employee><employee> employees = new List<Employee><employee>();
Employee emp = new Employee();
emp.FirstName = "johnson";
emp.LastName = " fernandes";
emp.Salary = 14000;
employees.Add(emp);</employee>

Step 6– Pass data from Controller

Hide   Shrink     Copy Code

public ActionResult GetView()


{
EmployeeListViewModel employeeListViewModel = new EmployeeListViewModel();

EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();


List<employee> employees = empBal.GetEmployees();

List<EmployeeViewModel><employeeviewmodel> empViewModels = new


List<EmployeeViewModel><employeeviewmodel>();

foreach (Employee emp in employees)


{
EmployeeViewModel empViewModel = new EmployeeViewModel();
empViewModel.EmployeeName = emp.FirstName + " " + emp.LastName;
empViewModel.Salary = emp.Salary.ToString("C");
if (emp.Salary > 15000)
{
empViewModel.SalaryColor = "yellow";
}
else
{
empViewModel.SalaryColor = "green";
}
empViewModels.Add(empViewModel);
}
employeeListViewModel.Employees = empViewModels;
employeeListViewModel.UserName = "Admin";
return View("MyView", employeeListViewModel);
}
</employeeviewmodel>

Step 7 – Execute and Test the Output


Press F5 and execute the application.

Talk on Lab 7
Can we make View a strongly typed view of List?

Yes, we can.

Why we create a separate class called EmployeeListViewModel, why didn’t we made View a
strongly typed view of type List<EmployeeListViewModel>?

If we use List directly instead of EmployeeListViewModel then there will be two problems.

1. Managing future presentation logic.


2. Secondly UserName property. UserName is not associated with individual employees. It is associated
with complete View.

Why we removed UserName property from EmployeeViewModel and made it part of


EmployeeListViewModel?

UserName is going to be same for all the employees. Keeping UserName property inside
EmployeeViewModel just increase the redundent code and also increases the overall memoty
requirement for data.

Learn MVC Project in 7 days – Day 3


Data Access Layer
A real time project is incomplete without Database. In our project we didn’t spoke database layer yet.
First Lab of Day 3 will be all about database and database layer.

Here we will use Sql Server and Entity Framework for creating Database and Database Access layer
respectively.

What is Entity Framework in simple words?

It’s an ORM tool. ORM stands for Object Relational Mapping.

In RDBMS world, we speak in terms of Tables and Columns whereas in .net world (which is an object
oriented world), we speak in terms of Classes, objects and properties.

When we think about any data driven application we end up with following two things.

 Write code for communicating with database (called Data Access Layer or Database logic)
 Write code for mapping Database data to object oriented data or vice versa.

ORM is a tool which will automate these two things. Entity framework is Microsoft ORM tool.

What is Code First Approach?

In Entity framework we can follow one of these three approaches

 Database First approach – Create database with tables, columns, relations etc. and Entity framework
will generates corresponding Model classes (Business entities) and Data Access Layer code.
 Model First approach – In this approach Model classes and relationship between them will be
defined manually using Model designer in Visual studio and Entity Framework will generate Data
Access Layer and Database with tables, columns, relations automatically.
 Code First approach – In this approach manually POCO classes will be created. Relationship between
those classes will be defined by means of code. When application executes for the first time Entity
framework will generate Data Access Layer and Database with tables, column and relations
automatically in the database server.

What is mean by POCO classes?

POCO stands for “Plain Old CLR objects”. POCO classes means simple .Net classes we create. In our
previous example Employee class was simply a POCO class.

Lab 8 – Add Data Access layer to the project


Step 1– Create Database

Connect to the Sql Server and create new Database called “SalesERPDB”.
Step 2 – Create ConnectionString

Open Web.config file and inside Configuration section add following section

Hide   Copy Code

<connectionStrings>
<add connectionString="Data Source=(local);Initial Catalog=SalesERPDB;Integrated
Security=True"
name="SalesERPDAL"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Step 3– Add Entity Framework reference

Right click the project >> Manage Nuget packages. Search for Entity Framework and click install.
Step 4 – Create Data Access layer.

 Create a new folder called “DataAccessLayer” in the root folder and inside it create a new class called
“SalesERPDAL”

 Put using statement at the top as follows.

 Hide   Copy Code
using System.Data.Entity;

 Inherit “SalesERPDAL” from DbContext


Hide   Copy Code
public class SalesERPDAL: DbContext
{
}

Step 5 – Create primary key field for employee class

Open Employee class and put using statement at the top as follows.

Hide   Copy Code

using System.ComponentModel.DataAnnotations;

Add EmployeeId property in Employee class and mark it as Key attribute.

Hide   Copy Code

public class Employee


{
[Key]
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Salary { get; set; }
}

Step 6 – Define mapping

Put following using statement in the top for “SalesERPDAL” class

Hide   Copy Code

using WebApplication1.Models;

Override OnModelCreating method in SalesERPDAL class as follows.

Hide   Copy Code

protected override void OnModelCreating(DbModelBuilder modelBuilder)


{
modelBuilder.Entity<employee>().ToTable("TblEmployee");
base.OnModelCreating(modelBuilder);
}
</employee>

Note: In above code snippet “TblEmployee” represents the table name. It automatically get created
in runtime.

Step 7 – Create property to hold Employees in Database


Create a new property called Employee in “SalesERPDAL” class as follows

Hide   Copy Code

public DbSet<employee> Employees{get;set;}


</employee>

DbSet will represent all the employees that can be queried from the database.

Step 8– Change Business Layer Code and get data from Database

Open EmployeeBusinessLayer class.Put using statement in the top.

Hide   Copy Code

using WebApplication1.DataAccessLayer;

Now change GetEmployees method class as follows.

Hide   Copy Code

public List<employee> GetEmployees()


{
SalesERPDAL salesDal = new SalesERPDAL();
return salesDal.Employees.ToList();
}
</employee>

Step 9 – Execute and Test

Press F5 and execute the application.

Right now we don’t have any employees in the database so we will see a blank grid.
Check the database. Now we have a table called TblEmployee with all the columns.

Step 9 – Insert Test Data

Add some dummy data to TblEmployee table.

Step 10 – Execute and test the application

Press F5 and run the application again.


Here we go 

Talk on Lab 8
What is DbSet?

DbSet simply represent the collection of all the entities that can be queried from the database. When
we write a Linq query again DbSet object it internally converted to query and fired against database.

In our case “Employees” is a DbSet which will hold all the “Employee” entities which can be queried
from database. Every time we try to access “Employees” it gets all records in the “TblEmployee” table
and convert it to “Employee” object and return the collection.

How connection string and data access layer is connected?

Mapping will be done based on name. In our example ConnectionString Name and Data Access
Layer class name is same that is “SalesERPDAL”, hence automatically mapped.

Can we change the ConnectionString name?

Yes, in that case we have to define a constructor in Data Access Layer class as follows.

Hide   Copy Code
public SalesERPDAL():base("NewName")
{
}

Organize everything
Just to make everything organized and meaningful let’s do couple of changes.

Step 1 - Rename

 “TestController” to “EmployeeController”
 GetView action method to Index
 Test folder (inside Views folder) to Employee
 and “MyView” view to “Index”

Step 2 – Remove UserName property from EmployeeListViewModel

Step 3 – Remove UserName from View

Open Views/Employee.Index.cshtml View and remove username from it.

In simple words, remove following block of code.

Hide   Copy Code

Hello @Model.UserName
<hr />

Step 2 – Change Index Action Method in EmployeeController

Accordingly Change the code in Index action in EmployeeController as follows.

Hide   Copy Code

public ActionResult Index()


{
employeeListViewModel.Employees = empViewModels;
//employeeListViewModel.UserName = "Admin";-->Remove this line -->Change1
return View("Index", employeeListViewModel);//-->Change View Name -->Change 2
}

Now at the time of execution URL will “…./Employee/Index”

Lab 9 – Create Data Entry Screen


Step 1 – Create action method
Create an action method called “AddNew” in EmployeeController as follows

Hide   Copy Code

public ActionResult AddNew()


{
return View("CreateEmployee");
}

Step 2 – Create View

Create a view called “CreateEmployee” inside View/Employee folder as follows.

Hide   Copy Code

@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CreateEmployee</title>
</head>
<body>
<div>
<form action="/Employee/SaveEmployee" method="post">
First Name: <input type="text" id="TxtFName" name="FirstName" value="" /><br />
Last Name: <input type="text" id="TxtLName" name="LastName" value="" /><br />
Salary: <input type="text" id="TxtSalary" name="Salary" value="" /><br />
<input type="submit" name="BtnSave" value="Save Employee" />
<input type="button" name="BtnReset" value="Reset" />
</form>
</div>
</body>
</html>

Step 3 – Create a link in Index View

Open Index.cshtml and add a hyperlink pointing to AddNew Action URL.

Hide   Copy Code

<ahref="/Employee/AddNew">Add New</a>

Step 4 –Execute and Test the application

Press F5 and execute the application


Talk on Lab 9
What is the purpose of form tag?

In day 1 of the series we have understood that “Web world won’t follow Event driven programming
model. It follows request-response model. End user make the request and server sends response.”
Form tag is one of the way to make request in HTML. As soon as the submit button inside form tag
gets clicked, a request will be sent to the URL specified in action attribute.

What is method attribute in Form tag?


It decides the type of request. Request may be one of the following four types - get, post, put and
delete.

As per the web standards we should use–

 Get - > When we want to get something


 Post -> When we want to create something
 Put -> When we want to update something
 Delete -> when we want to delete something.

How making request using Form tag is different from making request via browser address bar
or hyperlink?

When request is made with the help of Form tag, values of all the input controls are sent with the
request for processing.

What about checkbox, radio buttons and Dropdowns? Will values of this controls also sent?

Yes, All input controls (input type=text, type=radio, type=checkbox) and also dropdowns (which
represented as “Select” element).

How values will be sent to server?

When request is of type Get, Put or Delete, values will be sent as Query string parameters.

When it’s a post request values will be sent as posted data.

What is the purpose of name attribute in input controls?

As discussed before values of all input controls will be sent along with request when submit button is
clicked. It makes server receive more than one value at a time. To distinguish each value separately
while sending every value is attached with one key and that key will be simply “name” attribute.

Does name and id attribute serves same purpose?

No, as per last question “name” attribute will be used internally by HTML when the request is being
sent whereas “id” attribute will be used by developers inside JavaScript for some dynamic stuffs. 

What is the difference between “input type=submit” and “input type=button”?

Submit button will be specially used when we want to make request to the server whereas simple
button will be used to perform some custom client side actions. Simple button won’t do anything by
its own.
Lab 10 – Get posted data in Server
side/Controllers
Step 1 – Create SaveEmployee Action method

Inside Employee Controller create an action method called SaveEmployee as follows.

Hide   Copy Code

public string SaveEmployee(Employee e)


{
return e.FirstName + "|"+ e.LastName+"|"+e.Salary;
}

Step 2 – Execute and Test

Press F5 and execute the application.

Talk on Lab 10
How Textbox values are updated in Employee object inside action method?

In Asp.Net MVC there is a concept called as Model Binder.

 Model Binder will executes automatically whenever a request is made to an action method
containing parameter.
 Model binder will iterate though all primitive parameters of a method and then it will compare name
of the parameter with each key in the incoming data (Incoming data means either posted data or
query string).When match is found, corresponding incoming datawill be assigned to the parameter.
 After that Model binder will iterate through each and every property of each and every class
parameter and compare each property name with each key in incoming data.When match is found,
corresponding incoming value will be assigned to the parameter.

What will happen when two parameters are specified, one as “Employee e” and second as
“string FirstName”?

FirstName will be updated in both primitive FirstName variable and e.FirstName property.

Will Model Binder work with composition relationship?

Yes it will, but in that case name of the control should be given accordingly.

Example

Let say we have Customer class and Address class as follows

Hide   Copy Code

public class Customer


{
public string FName{get;set;}
public Address address{get;set;}
}
public class Address
{
public string CityName{get;set;}
public string StateName{get;set;}
}

In this case Html should look like this

Hide   Copy Code

...
...
...
<input type="text" name="FName">
<input type="text" name="address.CityName">
<input type="text" name="address.StateName">
...
...
...

Lab 11 – Reset and Cancel button


Step 1 – Start withReset and Cancel button

Add a Reset and Cancel button as follows


Hide   Copy Code

...

...

...

<input type="submit" name="BtnSubmit&rdquo; value="Save Employee" />

<input type="button" name="BtnReset" value="Reset" onclick="ResetForm();" />

<input type="submit" name="BtnSubmit" value="Cancel" />

Note: Save button and Cancel button have same “Name” attribute value that is “BtnSubmit”.

Step 2 – define ResetForm function

In Head section of Html add a script tag and inside that create a JavaScript function called ResetForm
as follows.

Hide   Copy Code

<script>
function ResetForm() {
document.getElementById('TxtFName').value = "";
document.getElementById('TxtLName').value = "";
document.getElementById('TxtSalary').value = "";
}
</script>

Step 3 – Implement cancel click in EmplyeeController’s SaveEmployee action method.

Change SaveEmployee action method as following

Hide   Copy Code

public ActionResult SaveEmployee(Employee e, string BtnSubmit)


{
switch (BtnSubmit)
{
case "Save Employee":
return Content(e.FirstName + "|" + e.LastName + "|" + e.Salary);
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}

Step 4 – Execute the application.

Press F5 and execute the application. Navigate to the AddNew screen by clicking “Add New” link.
Step 5 – Test Reset functionality

Step 6 – Test Save and Cancel functionality

Talk on Lab 11
Why same name is given to both Save and Cancel button?

We know that, as soon as submit button is clicked, a request is sent to the server.Along with the
request values of all the input controls will be sent.

Submit button is also an input button. Hence value of the submit button (which is responsible for the
request) will be sent too.

When Save button will be clicked, value of Save button that is “Save Employee” will be sent with
request and when Cancel button is clicked, value of Cancel button that is “Cancel” will sent with
request.
In Action method, Model Binder will do remaining work. It will update the parameter values with
values in input data (coming with request)

What are the other ways to implement multiple submit buttons?

There are many ways. I would like to discuss three of them.

1. Hidden Form element

Step 1 – Create a hidden form element in View as follows.

Hide   Copy Code

<form action="/Employee/CancelSave" id="CancelForm" method="get" style="display:none">

</form>

<form action="/Employee/CancelSave" id="CancelForm" method="get"


style="display:none"> </form>

Step 2 – Change Submit button to normal button and post above form with the help of JavaScript.

Hide   Copy Code

<input type="button" name="BtnSubmit" value="Cancel"


onclick="document.getElementById('CancelForm').submit()" />

2. Change action URL dynamically using JavaScript

Hide   Copy Code

<form action="" method="post" id="EmployeeForm" >


...
...
<input type="submit" name="BtnSubmit" value="Save Employee"
onclick="document.getElementById('EmployeeForm').action = '/Employee/SaveEmployee'" />
...
<input type="submit" name="BtnSubmit" value="Cancel"
onclick="document.getElementById('EmployeeForm').action = '/Employee/CancelSave'" />
</form>

3. Ajax

Instead of submit button use simple input button and onclick of it make pure Ajax request using
jQuery or any other library.

Why we have not used input type=reset for implementing Reset functionality?
Input type=reset control won’t clear the values, it just set the value to default value of a control.
Example:

Hide   Copy Code

<input type="text" name="FName" value="Sukesh">

In above example default value of control is “Sukesh”.

If we use input type=reset for implementing Reset functionality then by default “Sukesh” will be set
in the textbox every time “reset” button is clicked.

What if names are not matching with property names of the classes?

This is a very common question during interviews.

Let say we have HTML as follows

Hide   Copy Code

First Name: <input type="text" id="TxtFName" name="FName" value="" /><br />


Last Name: <input type="text" id="TxtLName" name="LName" value="" /><br />
Salary: <input type="text" id="TxtSalary" name="Salary" value="" /><br />

Now our Model class contain property names as FirstName, LastName and Salary. Hence default
model binder won’t work here.

In this situation we have following three solutions

 Inside action method, retrieve posted values using Request.Form syntax and manually construct the
Model object as follows.
Hide   Copy Code

public ActionResult SaveEmployee()


{
Employee e = new Employee();
e.FirstName = Request.Form["FName"];
e.LastName = Request.Form["LName"];
e.Salary = int.Parse(Request.Form["Salary"])
...
...
}

 Use parameter names and Creates Model object manually as follows.


Hide   Copy Code

public ActionResult SaveEmployee(string FName, string LName, int Salary)


{
Employee e = new Employee();
e.FirstName = FName;
e.LastName = LName;
e.Salary = Salary;
...
...
}

 Create Custom Model Binder and replace default model binder as follows.

Step 1 – Create Custom Model Binder

Hide   Copy Code

public class MyEmployeeModelBinder : DefaultModelBinder


{
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType)
{
Employee e = new Employee();
e.FirstName = controllerContext.RequestContext.HttpContext.Request.Form["FName"];
e.LastName = controllerContext.RequestContext.HttpContext.Request.Form["LName"];
e.Salary =
int.Parse(controllerContext.RequestContext.HttpContext.Request.Form["Salary"]);
return e;
}
}

Step 2- Replace default model binder with this new model binder

Hide   Copy Code

public ActionResult SaveEmployee([ModelBinder(typeof(MyEmployeeModelBinder))]Employee e,


string BtnSubmit)
{
......

What does RedirecttToFunction do?

It generates RedirectToRouteResultJust like ViewResult and ContentResult (discussed in Day 1),


RedirectToRouteResult is a child of ActionResult.It represents the redirect response. When browser
receives RedirectToRouteResult, it makes new request to new action method.

Note: Here browser is responsible for new request hence URL will get updated to new URL.

What is EmptyResult?

One more child of ActionResult. When browser receives EmptyResult as a response it simply displays
blank white screens. It simply represents “No Result”.

In our example this situation won’t happen. Just to make sure that all code paths returns a value
EmptyResult statement was written.
Note:When ActionMethod return type is Void, it is equivalent to EmptyResult

Lab 12 – Save records in database and update


Grid
Step 1 – Create SaveEmployee in EmployeeBusinessLayer as follows

Hide   Copy Code

public Employee SaveEmployee(Employee e)


{
SalesERPDAL salesDal = new SalesERPDAL();
salesDal.Employees.Add(e);
salesDal.SaveChanges();
return e;
}

Step 2 – Change SaveEmployee Action method

In EmployeeController change the SaveEmployee action method code as follows.

Hide   Copy Code

public ActionResult SaveEmployee(Employee e, string BtnSubmit)


{
switch (BtnSubmit)
{
case "Save Employee":
EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();
empBal.SaveEmployee(e);
return RedirectToAction("Index");
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}

Step 3 – Execute and Test

Press F5 and execute the application. Navigate to Data entry screen and put some valid values.
Lab 13 – Add Server side Validation
In Lab 10 we have seen basic functionality of Model Binder. Let understand a little more about same.

 Model binder updates the Employee object with the posted data.
 But this is not the only functionality performed by Model Binder. Model Binder also updates
ModelState. ModelState encapsulates the state of the Model.
 It have a property called IsValid which determines whether the Model (that is Employee object) gets
successfully updated or not.Model won’t update if any of the server side validation fails.
 It holds validation errors.
Example:ModelState["FirstName "].Errors will contain all errors related to First Name
 It holds the incoming value(Posted data or queryString data)
 It holds the incoming value(Posted data or queryString data)

In Asp.net MVC we use DataAnnotations to perform server side validations.

Before we get into Data Annotation lets understand few more things about Model Binder

How Model Binder work with primitive datatypes

When Action method contain primitive type parameter, Model Binder will compare name of the
parameter with each key in the incoming data (Incoming data means either posted data or query
string).

 When match is found, corresponding incoming data will be assigned to the parameter.
 When match is not found, parameter will be assigned with default value. (Default value – For integer
it is 0 (zero), for string it is null etc.)
 In case assignment is not possible because of datatype mismatch exception will be thrown.
How Model Binder work with classes

When parameter is a Class parameter, Model Binder will iterate through all properties of all the class
and compare each property name with each key in incoming data.

 When match is found,


 If corresponding incoming value is empty, then
 Null value will be assigned to property. If null assignment is not possible, default value will be set and
ModelState.IsValid will be set to false.
 If null assignment is possible but will be considered as invalid value because of the validation
attached to the property then null be assigned as value and ModelState.IsValid will be set to false.
 If corresponding incoming value is non empty,
 In case assignment is not possible because of datatype mismatch or Server side validation failure null
value will be assigned and ModelState.IsValid will be set to false.
 If null assignment is not possible, default value will be set
 When match is not found, parameter will be assigned with default value. (Default value – For integer
it is 0 (zero), for string it is null etc.)In this case ModelState.IsValid will remain unaffected.

Let’s understand same by adding validation feature to our on-going project.

Step 1 – Decorate Properties with DataAnnotations

Open Employee class from Model folder and decorate FirstName and LastName property with
DataAnnotation attribute as follows.

Hide   Copy Code

public class Employee


{
...
...
[Required(ErrorMessage="Enter First Name")]
public string FirstName { get; set; }

[StringLength(5,ErrorMessage="Last Name length should not be greater than 5")]


public string LastName { get; set; }
...
...
}

Step 2 – Change SaveEmployee Action method

Open EmplyeeController and Change SaveEmployee Action method as follows.

Hide   Copy Code

public ActionResult SaveEmployee(Employee e, string BtnSubmit)


{
switch (BtnSubmit)
{
case "Save Employee":
if (ModelState.IsValid)
{
EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();
empBal.SaveEmployee(e);
return RedirectToAction("Index");
}
else
{
return View("CreateEmployee ");
}
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}

Note: As you can see, When ModelState.IsValid is false response of SaveEmployee button click is
ViewResult pointing to “CreateEmployee” view.

Step 3 – Display Error in the View

Change HTML in the “Views/Index/CreateEmployee.cshtml” to following.

This time we will format our UI a little with the help of “table” tag;

Hide   Shrink     Copy Code

<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" id="TxtFName" name="FirstName" value="" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("FirstName")
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" id="TxtLName" name="LastName" value="" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("LastName")
</td>
</tr>

<tr>
<td>
Salary:
</td>
<td>
<input type="text" id="TxtSalary" name="Salary" value="" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("Salary")
</td>
</tr>

<tr>
<td colspan="2">
<input type="submit" name="BtnSubmit" value="Save Employee" />
<input type="submit" name="BtnSubmit" value="Cancel" />
<input type="button" name="BtnReset" value="Reset" onclick="ResetForm();" />
</td>
</tr>
</table>

Step 4 – Execute and Test

Press F5 and execute the application. Navigate to “Employee/AddNew” action method and test the
application.

Test 1

Test 2

Note: You may end up with following error.


“The model backing the 'SalesERPDAL' context has changed since the database was created.
Consider using Code First Migrations to update the database.”
To remove this error, simply add following statement in Application_Start in Global.asax file.

Hide   Copy Code

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SalesERPDAL>());

Database class exists inside System.Data.Entity namespace

If you are still getting the same error then, open database in Sql server and just delete
__MigrationHistory table.

Soon I will release a new series on Entity Framework where we will learn Entity framework step by
step. This series is intended to MVC and we are trying to stick with it. 

Talk on lab 13
What does @Html.ValidationMessage do?

 @ means it’s a razor code


 Html is an instance of HtmlHelper class available inside view.
 Validation Message is a function of HtmlHelper class which displays the error message

How ValidationMessage function works?

ValidationMessage is a function. It executes at runtime. As we discussed earlier, ModelBinder


updates the ModelState. ValidationMessage displays the error message from ModelState based on
Key.

Example: ValidationMessage(“FirstName”) displays the error message related to First Name.

Do we have more attributes like required and StringLength?

Yes, here are some

 DataType – Make sure that data is of particular type like email, credit card number, URL etc.
 EnumDataTypeAttribute–Make sure that value exist in an enumeration.
 Range Attribute – Make sure that value is in a particular range.
 Regular expression- Validates the value against a particular regular expression.
 Required – Make sure that value is provided.
 StringthLength – Validates the string for maximum and minimum number of characters.

How Salary is getting validated?


We have not added any Data Annotation attribute to Salary attribute but still it’s getting validated.
Reason for that is, Model Binder also considers the datatype of a property while updating model.

In Test 1 – we had kept salary as empty string. Now in this case, as per the Model binderexplanation
we had (In Lab 13), ModelState.IsVaid will be false and ModelState will hold validation error related
to Salary which will displayed in view because of Html.ValidationMessage(“Salary”)

In Test 2 – Salary data type is mismatched hence validation is failed.

Is that means, integer properties will be compulsory by default?

Yes, Not only integers but all value types because they can’t hold null values.

What if we want to have a non-required integer field?

Make it nullable?

Hide   Copy Code

public int? Salary{get;set;}

How to change the validation message specified for Salary?

Default validation support of Salary (because of int datatype) won’t allow us to change the validation
message. We achieve the same by using our own validation like regular expression, range or Custom
Validator.

Why values are getting cleared when validation fails?

Because it’s a new request. DataEntry view which was rendered in the beginning and which get
rendered later are same from development perspective but are different from request perspective.
We will learn how to maintain values in Day 4.

Can we explicitly ask Model Binder to execute?

Yes simply remove parameters from action method. It stops default model binder from executing by
default.

In this case we can use UpdateModel function as follows.

Hide   Copy Code

Employee e = new Employee();


UpdateModel<employee>(e);
</employee>
Note: UpdateModel won’t work with primitive datatypes.

What is the difference between UpdateModel and TryUpdateModel method?

TryUpdateModel will be same as UpdateModel except one added advantage.

UpdateModel will throw an exception if Model adaption fails because of any reason. In case of
UpdateModel function ModelState.IsValid will not be of any use.

TryUpdateModel is exactly same as keeping Employee object as function parameter. If updating fails
ModelState.IsValid will be false;

What about client side validation?

It should be done manually unless and until we are using HTML Helper classes.

We are going to talk about both manual client side validation and automatic client side validation
with the help of HTML helper classes in day 4.

Can we attach more than one DataAnnotation attribute to same property?

Yes we can. In that case both validations will fire.

Lab 14 – Custom Server side validation


Step 1 – Create Custom Validation

Open Employee.cs file and create a new class Called FirstNameValidation inside it as follows. 

Hide   Copy Code

public class FirstNameValidation:ValidationAttribute


{
protected override ValidationResult IsValid(object value, ValidationContext
validationContext)
{
if (value == null) // Checking for Empty Value
{
return new ValidationResult("Please Provide First Name");
}
else
{
if (value.ToString().Contains("@"))
{
return new ValidationResult("First Name should Not contain @");
}
}
return ValidationResult.Success;
}
}

Note: Creating multiple classes inside single file is never consider as good practice. So in your sample
I recommend you to create a new folder called “Validations” in root location and create a new class
inside it.

Step 2- Attach it to First Name

Open Employee class and remove the default “Required” attribute from FirstName property and
attach FirstNameValidation as follows.

Hide   Copy Code

[FirstNameValidation]
public string FirstName { get; set; }

Step 3 – Execute and Test

Press F5. Navigate to “Employee/AddNew” action.

Test 1

Test 2

You might also like