Showing posts with label MVC FAQS. Show all posts
Showing posts with label MVC FAQS. Show all posts

Oct 27, 2015

ChildActiononly Attribute in Mvc

Step 1: Create a blank asp.net mvc 4 application

Step 2: Add HomeController. Copy and paste the following code.


public class HomeController Controller
{
    // Public action method that can be invoked using a URL request
    public ActionResult Index()
    {
        return View();
    }

    // This method is accessible only by a child request. A runtime 
    // exception will be thrown if a URL request is made to this method
    [ChildActionOnly]
    public ActionResult Countries(List<String> countryData)
    {
        return View(countryData);
    }
}


Step 3: Right click on the "Countries()" action method and add "Countries" view. This view will render the given list of strings as an un-ordered list.

@model List<string>

@foreach (string country in Model)
{
    <ul>
        <li>
            <b>
                @country
            </b>
        </li>
    </ul>
}

Step 4: Right click on the "Index()" action method and add "Index" view.  Copy and paste the following code. Notice that, to invoke childaction, we are using Action() HTML Helper.

<h2>Countries List</h2>
@Html.Action("Countries"new { countryData = new List<string>() { "US", "UK", "India" } })

Please Note: Child actions can also be invoked using "RenderAction()" HTMl helper as shown below.
@{
    Html.RenderAction("Countries"new { countryData = new List<string>() { "US", "UK", "India" } });
}

Points to remember about "ChildActionOnly" attribute
1. Any action method that is decorated with [ChildActionOnly] attribute is a child action method.

2. Child action methods will not respond to URL requests. If an attempt is made, a runtime error will be thrown stating - Child action is accessible only by a child request.

3. Child action methods can be invoked by making child request from a view using"Action()" and "RenderAction()" html helpers.

4. An action method doesn’t need to have [ChildActionOnly] attribute to be used as a child action, but use this attribute to prevent if you want to prevent the action method from being invoked as a result of a user request.

5. Child actions are typically associated with partial views, although this is not compulsory.

6. Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked using Action() or RenderAction() helpers. 

7. Using child action methods, it is possible to cache portions of a view. This is the main advantage of child action methods. We will cover this when we discuss [OutputCache] attribute. 

Oct 16, 2015

MVC which submit button has been pressed

input name="submit" type="submit" id="submit" value="Save" />
input name="submit" type="submit" id="process" value="Process" />
 
public ActionResult Index(string submit)
{
    Response.Write(submit);
    return View();
}
 
 
You can of course assess that value to perform different operations with a switch block
 
public ActionResult Index(string submit)
{
    switch (submit)
    {
        case "Save":
            // Do something
            break;
        case "Process":
            // Do something
            break;
        default:
            throw new Exception();
            break;
    }

    return View();
}.
 
 
 
 
 
  

Oct 9, 2015

Why should prefer REST based services over SOAP

1-REST permits many different data formats whereas SOAP only permits XML.

2-JSON usually is a better fit for data and parses much faster. REST allows
 better support for browser clients due to its support for JSON. 

3-REST has better performance and scalability. 

 4-REST reads can be cached, SOAP based reads cannot be cached.

 5-SOAP is a protocol its Simple Object Access Protocol and rest is an Architecture .REST stands for Representational State Transfer. 

1. The RESTful Web services are completely stateless. This can be tested by restarting the server and checking if the interactions are able to survive. 

2. Restful services provide a good caching infrastructure over HTTP GET method (for most servers). This can improve the performance, if the data the Web service returns is not altered frequently and not dynamic in nature. 

3. The service producer and service consumer need to have a common understanding of the context as well as the content being passed along as there is no standard set of rules to describe the REST Web services interface. 

4. REST is particularly useful for restricted-profile devices such as mobile and PDAs for which the overhead of additional parameters like headers and other SOAP elements are less.

 5. REST services are easy to integrate with the existing websites and are exposed with XML so the HTML pages can consume the same with ease. There is hardly any need to refactor the existing website architecture. This makes developers more productive and comfortable as they will not have to rewrite everything from scratch and just need to add on the existing functionality.

 7. REST permits many different data formats where as SOAP only permits XML. 

6. REST-based implementation is simple compared to SOAP. 

Sep 25, 2015

Controllers In Mvc

Controllers are basically nerve of ASP.Net MVC as it is going to be the 1st recipient which is going to interact with incoming HTTP Request. So, controllers are going to decide which model is going to be selected, then taking the data from the model and passing the same to the respective
view, hence finally view is going to be rendered. So, controllers in a nutshell are basically controlling the overall flow of the application taking the input and rendering the proper output. Since, we have selected internet template while building the application, so we have been presented with two default controllers called as


Home Controller: - It will render the home page of the application.
Account Controller: - It will render the Login/Registration page of the application



Below, is the sample snapshot of the Home controller being created by the Visual Studio.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace MovieReview.Controllers
{


public class HomeController : Controller
{


public ActionResult Index()
{


ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC
application.";
return View();
}


public ActionResult About()
{


ViewBag.Message = "Your app description page.";
return View();

}

public ActionResult Contact()
{


ViewBag.Message = "Your contact page.";
return View();


}


}


}

Now, when you run the application by clicking F5 button, it will simply render the Home view with the above welcome message printed on screen as shown below in the snapshot.
However, you can verify the same by putting one debug point in the home controller and see how the control is flowing and how view is getting rendered over here.



Now, when you run the application, you will see that control has hit the break point and then it rendered the corresponding view with the above details and the static details which is mentioned in the view

 We’ll discuss View in more detail in the next chapter. But for now just understand that Home Controller’s Index action is going to return the Index View under the Views  Home directory.
There is one more important point to notice here, that development box is running on the IIS Express.






Now, when you right-click on IIS Express you will see the currently running application on it and the random port which is allotted to it.








IIS Express is basically development version of Visual Studio which comes with Visual Studio 2012+ platform. It allocates random port for your website. In our case this is http://localhost:1033/.


Working with your 1st Controller:


Let’s get started by creating your 1st controller. This controller will simply search movies. Then, subsequently we’ll start adding some more features to the item displayed on the screen like when you click on the movie; corresponding movie details will flash on screen. However, it’s worth
time spending to understand the routing before jumping to write our 1st controller. Obviously, we’ll do deep dive about routing in routing chapter. But, 1st let’s understand few basic concepts of routing.


One of the core questions which you must be thinking that how ASP.Net MVC knows to load the index action when the URL http://localhost:1033/ is invoked, and the answer lies in the routing engine. The Routing Engine is the core concept of the ASP.Net MVC; it’s not coupled with
MVC Framework. Why am saying this, because we can use the routing engine to route the request for Web Forms, WCF Services etc. But, here in MVC we use this routing engine to redirect request to our controllers. In order to execute the same, we give the routing engine a map to follow using “MapRoute” API.


routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);



So, basically what a route map does, it provides a friendly name to the route, a pattern to follow
and default parameters for the route. So, if you think about the job of the routing engine, its job is pretty simple. Its job is to examine the URL and figure out where to send the request for processing. When, it examines the URL, it picks up the little pieces from the URL which tells the routing engine, where to send the request. In an MVC Application framework, we provide
nomenclature “Controller/Action/Id(somedata)”. So, if the routing engine doesn’t find the specific piece of data inside the URL, like controller name or action name, then it can use the default values assigned in the Map. In the above piece of code, it is “Home” controller and “Index” action are default values. Now, there are certain application level settings which are predefined in “Global.asax” file. This file is really interesting file in ASP.Net. It derives the application. Below is the sample code of this Global.asax file.





public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();


WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();



}
}


Here, you can see that this class is derived from http application and this allows us to drill into some application level events like “Application_Start”. So, this method will be processed by ASP.NET, before you process your 1st http request. So, it means when your application starts running, the code here will execute one time before any controllers start executing. So, this is the
place where in we put some configuration related changes for example Routing Configuration. 

The route configuration is done by 
“RouteConfig.RegisterRoutes(RouteTable.Routes)”. So,
here we are going to pass the routing table also known as “Global Routing Table”, values which contain all the routes for the entire application. This table will be empty initially, but when we call routes, it will add entries in the routing table. Now, let’s inspect the values inside the route
collection.  


public ActionResult Index()
{
var Controller = RouteData.Values["controller"];
var Action = RouteData.Values["action"];
var Id = RouteData.Values["id"];
string Output = string.Format("Controller = {0}, Action= {1}, Id= {2}",
Controller, Action, Id);
ViewBag.Message = Output;
return View();
}


Now, when I build the solution and run the app, it will produce me the below result



Now, if you see the above screen shot, it presented the Controller’s name and Action name. However, if you see that Id field is blank here, because while running the app, I have not invoked
the app with any parameters, hence Id field is blank. However, there are other ways as well to grab these values. We’ll see the same in some time.
Now, in this application I would like segregate my custom route with the default Route. So, let’s go to “RouteConfig.cs” file under “App_Start” folder. Here, am going to write my custom route.
However, before jumping directly to write a new route, let’s 1st understand, why it is required to write another one when already default route is there. Consider a scenario where in any user comes in and search for a movie say “Movie/Avatar”. In this case, Avatar will be treated as parameter name not like action method, so in this kind of scenario our default route won’t work
significantly. So, in order to fix the same I’ll write below route. Also, route placement is equally important. Because “Default Route” is very greedy, it matches almost any pattern. Note that route works on
the principle first match wins, so, it’s always suggested to place your new route in front of the default route. Also, as per MVC convention route name has to be unique. So, two routes cannot have the same name.


//Movie/Avatar
routes.MapRoute("Movie",
"Movie/{name}",
new { controller = "Movie", action = "Search", name = "" });
Now, with this new route in place, let’s build the app and try to navigate
(http://localhost:1033/Movie/Avatar) to the above mentioned URL and see the result.







Well, the above result was obvious; because I told to go and find out the “Movie Controller”, but since I have not created the movie controller yet, hence it presented me the 404 error. Now, let me go ahead and create my 1st controller. Right-Click the controller’s folder and say add new controller and then give the name as Movie Controller








Now, as you can see in the above screen shot I have added Movie Controller as an empty MVC controller. I took this liberty to write the entire code right from the scratch in front of you. So, the code for the same looks like as shown below. However, in the coming chapters we’ll learn the usage of other scaffolding techniques listed in the dropdown.







Now, here in the above screen shot as you can see that it created the default action method with the name “Index”. However, I have designed the route in such a way that it will look for “Search” action by default. Hence, let me go ahead and rename the Index action to Search action. Also,


instead of returning view for now I’ll just return Content so that I don’t have to create view necessarily and also my purpose is served






So, now when I build the page and refresh the same, it will simply return me content on the
browser.





passed in. However, there are couples of ways to fetch the route data from the URL, one way which I explained earlier in this chapter using the “RouteData” data structure and grab the value
for the same. However, MVC framework also provided simple way to address this problem and that is by using the parameter inside the action method.
So, if you add a parameter to this method, what MVC framework will do, it will go and look for the value that matches the parameter name and it return it to you. Basically, it will apply all the permutation and combination to find out the parameter value for you, it will search in the Route
data; it will also inspect the query string and in the form posted value. So, in this case


“/Movie/Avatar”, MVC framework will decide that I need a parameter with “UserInput”, and then this will get picked from the URL and that will get automatically passed in to me.





Here, as you can see in the above screenshot in order to sanitize the user input I have used

“Server.HtmlEncode”, this will simply convert any kind of malicious script in plain text. If I would have been returning the same in view, it could have been automatically taken care for me.
But, since I am returning the same with content view, hence I need to return the sanitized input to prevent any kind of scripting attack. Now, when I build and refresh the same, it will present me the below output.





You can also inspect the value for the same as well.






However, in the current scenario if I remove the parameter name and then invoke the URL that
will work fine as shown below.



Reason for this is the default value of the route, in the route I have mentioned “name=””” which means if nothing is getting passed in, then simply pass in the empty value as default parameter value. However, if I remove the name parameter from the route and then build and refresh the
page, then it will result me error as shown below.









So, in order to fix this I can go ahead and allow optional parameters for the parameter value as shown below




What this is doing that it just ensuring that even if the parameter didn’t mention in the url, it’s ok it will not result 404 error, it will just print out the empty result. Also, in order to prove the point that MVC framework looking for the parameter values at different locations; let me try one
example with query string.





We can also provide certain default values if nothing is passed in as parameter in the URL. In that case, it will simply return the default value on the screen as shown below.











 


Creating a MVC Application

we’ll be building a simple web app for “Movie Review” where in I’ll walk you through all the tiny steps involved in building the site. So, let’s get started. Before we begin, we must install the prerequisites for making this app. Now, to create a MVC Application, open the Visual Studio, click on New Project and select the below mentioned project as shown in the snapshot.








Note: - Here am using Visual Studio 2013 Ultimate Version.
Now, as soon as you select the MVC 4 web application, it will present couple of differentapplication templates option as shown ahead in the screen shot.





Empty Template:- Empty template will just have the basic folder structure that’s it and nothing more than that.

Basic Template:- The basic template will give you the MVC infrastructure in the solution.However, basic templates are for experienced MVC guys who want to customize the solution their way.


Internet Application:- Internet Application is the one which I am interested in as you can see in the above screen shot. However, it will give all the required dependencies in my solution structure to get started with my web application.
Intranet Application:- Intranet application is the one which deals with Windows Authentication. So, once you select this option, your app gets automatically configured with windows related settings.


Mobile Application:- Mobile application is the one which is included with MVC 4. The mobile application is preconfigured with JQuery Mobile. It helps developer to create just mobile sites. It includes themes which is supported by mobiles, touch enabled UI etc.


Web API: - Web API terminology will be discussed in detail later in this book. However, for now you just need to know that Web API is basically a framework which supports creating HTTP services.


Single Page Application: - SPA is a new terminology which offers building Single Page Application, focused mainly on client side interactions using tons of JavaScript and different JS Frameworks like Knockout, Durandal, Angular etc. This kind of web application is highly


interactive and feature rich for ex: - Gmail, Outlook etc.


Facebook Application: - Facebook application is I would say a kind of API support which offers developer to use the Facebook API in their application to build a Facebook centric website. This is really a cool stuff. 


Now, the next option which I have selected above is razor as view engine, so if I click on this dropdown I could see two options available as Razor and ASPX.



I also have a habit of checking Unit Test Project as you can see below in the screen shot. So, upon checking this checkbox, Visual Studio will create o n e more project for me in thesolution which is going to be Test project. Here, I can go ahead and write my test cases against any specific module or scenarios






 So, when you click on the dropdown of Test framework, you will see only one test framework in there. However, Microsoft has given an option to developers to install their friendly testing framework like NUnit, XUnit, etc. So, once these frameworks will get installed, this will get added in the dropdown box.

How MVC Applications are Structured:-
 
Below is the snapshot of the MVC application structure. This gives a brief idea that how your simple MVC app is structured initially.








Below I have listed specific directories which are there in the solution and their meaning.

Models:- Section containing all the classes related for fetching the data and manipulating the same.


Views:- Section containing all the UI related stuffs. These are the ones which are going to be rendered based on controller’s action.


Controllers:- Section where in the entire controller classes are placed which basically handles all the incoming requests from the browser.


Scripts:- Section where in all the scripts related stuffs are placed.


Images:- Section where in all the images are placed which is used across your site.


Filters:- Section where in all the filters are placed. We’ll do deep dive usage of filters later in coming chapters.


App Data: - Section where in all the data files are stored meant for reading and writing the same.



App Start: - Section where in all configurable stuffs resides like Web API, Routing etc.


Note: - This is basic internet app MVC structure. However, please note that MVC Framework never enforces any kind of folders organization. You can obviously customize the folders your way, like in many enterprise projects Models go in a separate class library project just to make sure reusability. However, you could do higher level of separation, it entirely depend on you.




MVC Life Cycle

diagram you will come to know How MVC application behaves when it’s invoked from the browser. So, as you see in the diagram, as soon as request comes from the browser, it is picked up by the routing engine. Hence, ASP.NET Routing is the first step in MVC Life cycle. Basically it is a pattern matching system which matches the request’s pattern against the registered patterns in
the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. If the routing engine doesn’t match the pattern then it returns 404 HTTP Status code.


Then, MVC handler implements IHttpHandler interface and further process the request by using ProcessRequest method. Then in third step MVCHandler uses the IControllerFactory instance and tries to get a IController instance. If successful, then Execute method is called. Now, once the controller has been instantiated, Controller's ActionInvoker checks which action to invoke on
the controller. Next, the action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JSONResult, FileResult, and EmptyResult. Now, the next step is the execution of the View Result which involves the
selection of the appropriate View Engine to render the View Result. It is basically handled by IViewEngine interface of the view engine. Now, at last Action method returns a string, binary file or a JSON Formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser by using the current view engine.














Brief History of MVC Pattern

ASP.NET MVC 1 Features:-
Here, in this section apart from separation of concerns, Unit tests were added. So, while writing any project, you could write unit test for specific modules side by side. MVC 1st was released on 13th March 2009.


ASP.NET MVC 2 Features:-

 
ASP.NET MVC 2 was released just in a span of 1 year. This has got some really cool features which make MVC more robust and powerful. This version was released on March 2010. Some of the features of MVC 2 have been listed below:-


• UI Helpers with Scaffolding templates.
• Model validation on Client and Server side.
• Strongly typed HTML Helpers.
• Enhanced Visual Studio tooling.


ASP.NET MVC 3 Features:-

 
ASP.NET MVC 3 was officially released in 2011. MVC 3 has come with major improvements in many sections. Some of the MVC 3 features are listed below:-


• Inclusion of Razor View Engine.
• .Net 4 Data annotations.
• Robust model binding and validation.
• Inclusion of Global Action Filters.

Nice JS, JQuery support. Also, included Unobtrusive JavaScript
validation.
• JSON Binding
• NuGet Integration to resolve the software dependencies on the
fly.


ASP.NET MVC 4 Features:-
 
ASP.NET MVC 4 has done value addition on MVC 3. On the other hand it has become a complete web development package as a whole which offers developer complete suites of development stack. Some of the common features are listed below:-


• ASP.NET Web API
• Improved Project Templates. Added new Ones
• Inclusion of Mobile Projects using JQuery Mobile.
• Various Display Modes
• Asynchronous Controllers
• Bundling and Minification


ASP.NET MVC 5 Features:-

 
Again ASP.NET MVC 5 has done many value additions to MVC 4. But, all of these changes are around its scaffolding templates, authentication technique, Bootstrap and many more. Some of the common features are listed below.


• Scaffolding
• ASP.Net Identity
• One ASP.Net
• Bootstrap
• Attribute Routing
• Filter Overrides


ASP.NET MVC 6 Features:-
 
ASP.NET MVC 6 in many terms is a unique framework as it’s a major change in MVC. Allthese features will be discussed in the last chapter in detail, where we’ll see the glimpse of MVC 6. Below, I have listed some of the common features of MVC 6.

• Common Framework for MVC, Web API and Web Pages
• Smooth Transiting from Web Pages to MVC
• Built DI First
• Runs on IIS or Self Host
• Based on the new Request Pipeline in ASP.NET vNext
• Runs Cloud Optimized
• No Build Dependency
• Enhanced developer experience
• Open Source
• Cross-Platform Support