Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • ASP.Net MVC-What's inside-Part2

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 357
    Comment on it

    This is the continuation of Part 1 of article-ASP.Net MIC-What's inside
    Now we come to 3 folders which are building blocks of any MVC application. So let us start with controller.
    Controller:-
         Here we can create controllers(Remember that entry point in previous article,or C of CMV). You get some of the controllers already created for you. Controller is a class file which inherits from Controller class of System.web.MVC namespace. Things getting a little "Cody" here? Don't worry, just correlate the sentences with what you find in your application(If you are following the steps). alt text

    Fig.8-Structure of a Controller.cs

    Now we see some methods in this HomeController.cs(Remember,the controller suffix is almost mandatory until you define your own controller.) . These methods are actions which get executed when a request is made (like create,edit,login etc).

    Now can you create a relation here. Your next question might be-between what?

    Just go through the previous articles and you'll find a relation among routeConfig.cs and Controller. Don't want to go back all the way back?Okay,Don't go to previous articles,just go to the explanation of routeConfig.cs.

    In routeConfig.cs we had controller and index parameters with values "Home" and "Index" respectively. So it relates to here in the controller and tells us that by default(if we use default route) the index method of Home controller will be executed.

    The ActionResult return type in method represents the result of an action method. Means whenever a user sends a request by clicking on button on interface or loading of a page,the request includes information that the MVC framework uses to invoke an action method.

    There are multiple type of action results which derive from ActionResult like

    1-ViewResult - if you want to return a View
    2-FileResult - if you want to download a file
    3-JsonResult - if you want to serialize some model into JSON
    4-ContentResult - if you want to return plain text
    5-RedirectResult - if you want to redirect to some other action
    6-HttpUnauthorizedResult - if you want to indicate that the user is not authorized to access this action

    We can create a view by right clicking the controller method name and clicking the option" Add View". After that you are presented with a window like following:-

    alt text

    Fig.9-Adding a View

    Try keeping the name as it is. And if you want to change name,please change the name of your controller method. After clicking the add button you create a view.The where part is explained in the View section. And one thing that is new to you here is partial view(the check box) which is also explained in the same View section.

    Model:-
        The model is a conceptual data representation of your database table. In other words we can say that the model is a class file in which we have properties which are mapped to our database table(as per requirement).
    We can have the validations in model. The binding logic may be there in the model,but for the separation of concerns,keep the binding logic in a separate file.

    View:-
        The views are the user interface part of MVC application. They are like webforms .aspx page(I said like,not exactly webforms i.e. only for reference). The views folder here contains multiple sub folders. Let's take a look.

    I'll divide these sub folders in two parts. The first part contains three folders;

    1-Account
    2-Home
    3-Manage

    What's important here? Can you guess? As I think,folder names are. Take a closer look at the names of folders. And correlate them to controller names. Yeah,you got it right,there is a folder for every controller you create. And if we expand them,we find the views(.cshtml) exactly matching the name of methods in it. And don't worry,you don't have to maintain it,MVC framework maintains it automatically,another example of "Convention over Configuration".

    Now take a look at any view(.cshtml),let's say Index.cshtml in Home folder. And when you open a view, all of your understanding flow until now comes to a sudden halt. Where is the HTML,HEAD and BODY etc?

    So let's take our characters webforms developer and MVC developer in picture again.:-)

    Webforms Developer:-"That's why I don't want to use MVC. My webform has a structure,in MVC you are writing whatever you want. That's not for me."

    MVC Developer:-We're not writing whatever we want? We've got a structure in there.

    Webforms developer:-What type of structure that is? You blew up the head and body of HTML,and you call that a structure. This time I am not convinced.I need explanation....explaaaaaaaaaiiin..

    MVC Developer:- Hey..hey..calm down. We didn't blew up the HTML. We have it. But reorganized it as per the rule "Convention over Configuration". You still have one folder left. Let me explain about it and then we'll talk.

    Webforms Developer:- What folder?

    MVC Developer:-Shared Folder in Views.

    Webforms Developer:-We have four files here. Which one should I see?

    MVC Developer.:-The most important file is _Layout.cshtml. Open it and you'll find something.

    Webform Developer:-Hey. We got HTML tags. But what are those weird things between tags. Never seen them before? Explanation?

    MVC Developer:-Let's get your weird things into a list.

    1-Why this is written like this?
    2-What is "@"?
    3-@Styles.Render("~/Content/css")&@Scripts.Render("~/bundles/modernizr")

    4-@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    5-@Html.Partial("_LoginPartial")
    6-@RenderBody()
    7-@RenderSection("scripts", required: false)

    Why this is written like it?:-
         This is the first question which comes in to mind. So do you remember Master Pages in Asp.net Webforms? What was the idea behind that?

    The same look and feel across the application. So these _layout pages are implementing the same concept in MVC way.

    So your _layout.cshtml page acts as a Master page for the views you create. And here comes the next question.

    If this is the page with HTML,what are those .cshtml files in Home and Account folders. Everything will be clear once you go through the explanation of list items.

    @:-
         What is that @ sign written everywhere? Is it a new language?
    It is not a new language. This is a new view engine(just like you had aspx view engine for your webforms) named Razor from Microsoft. It has a new syntax which has @ as a placeholder or identifier of a code block inside HTML. Razor is not a complete replacement of Aspx syntax. You can still use that<%--%> syntax if you like but razor syntax is clean. Let's take an example of for loop :-
    in aspx-

    <ul>
        <%foreach (var item in Products)
            {  %>
                 <% if (item.IsInStock)
                      { %>
                             <p><%=item.ProductName%> is in stock</p>
                       <% }
                     else
                      { %>
                            <p><%=item.ProductName%> is not in stock</p>
                      <% } %>
        <%} %>
    </ul> 
    

    in Razor-

    <ul>
        @foreach (var item in Products)
        {
                   @if(item.IsinStock)
                   {   
                       @item.ProductName is in stock
                   } else {
                       @item.ProductName is in stock
                   } 
        }
    </ul>  
    



    You can see the cleanliness in code. For any code block,you just need to put @,nothing else. You can always use your aspx engine but a cleaner syntax is good for project maintenance and development.

    Aspx engine might be old but it is not that dull. It is a bit faster than razor engine but again,MS may improve Razor engine to the level of current aspx engine in near future and also that "bit" is not large enough to hamper the performance drastically. But if you still want to do every bit for performance,use aspx engine for now.

    @Styles.Render("~/Content/css")&@Scripts.Render("~/bundles/modernizr"):-
         This heading is just copied from the layout.cshtml page for an easy understanding. Do you remember the bundleConfig.cs in App_Start folder. Open that file again. This syntax is directly related to that file and it's methods. How?
    We've got a registerbundle method there. And inside that method let's take the first block of the code for our consideration:-

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));


    what is the explanation of that code? Let's start from endpoint of code. That code says that"Make a bundle of all jQuey files with(physical path given) some versions like1.1.10 etc,name it with a virtual path of (bundle/jquery) and add this jQuery bundle as a new bundle to bundle collection(parameter in registerbundles method)". And read the line for 10 times if you have to because this it what the code says,nothing more,nothing less.

    Same sentence is right for all the .Add code blocks in registerBundle method. Only name and the path changes. The first path from given from the endpoint is physical path and the second one is virtual.

    Now we can come to the script.Render and style.Render methods. These methods simply reference those bundles in HTML. Remember how we did the same referencing in webforms?

    We referenced each file individually whether it was css or js.
    So suppose we have 5 jQuery files,5 CSS files,4 custom js files.
    Now if we count them there are 14 files. If we reference them individually like we did in web forms,they will create 14 request cycles,1 for each file.

    With bundling similar files into one,we can reduce the cycles from 14 to to 3,1 bundle for each group of files. And this is the concept of"Bundling and Minification" which we talked about.
    Remember,MVC doesn't prevents you from referencing files in webforms manner. You can still reference the files in webforms way.

    @Html.ActionLink():-
        These are called HTML helpers for creating HTML controls on the fly. You can get more of the controls like form,radiobutton etc. For example the syntax

    "@Html.ActionLink("About this Website", "About") " creates the code
    < a href="/Home/About"> </ a> after getting rendered by Razor view engine.

    @Html.Partial("_LoginPartial"):-
        This syntax is like .ascx(user controls) concept of web forms and the how part takes us to the types of view.
    When we create a view,we see an option of creating a partial view. This is a type of view which can be thought as a user control of webforms. We see the suffix "Partial" in the shared folder in login. That tells us that that file is a partial view(User control is a reference here,not to be taken as real name of a partial view. It is just used for understanding purpose).

    No we know what a partial view is. So the syntax with that ".Partial" tells that here a partial view will be attached and will be called. In current project scenario we don't require the login page as a full blown .cshtml page because the UI contains lesser controls and we might need to call it often.

    @RenderBody():-
        This is the core part where body of HTML resides.You can think of it like the "ContentPlaceHolder" of webforms(think only for the sake of understanding,don't take it for sure). Just like the content pages do have a placeholder in master pages named "ContentPlaceHolder",the views of MVC have a placeholder for them in _Layout.cshtml which is Renderbody.

    @RenderSection("scripts", required: false):-
         A layout page can only contain one RenderBody method, but can have multiple sections. To create a section you use the RenderSection method. The difference between RenderSection and RenderPage is RenderPage reads the content from a file; whereas RenderSection runs code blocks you define in your content pages. For Example:

    Define a section:-

    @section header{
    <h1>Header Content</h1>
    }
    

    Render it:-

    @RenderSection("header") 
    

    If you want to make it optional:-

    @RenderSection("header",false) 
    

    If you want to make it mandatory:-

    @RenderSection("header",true) 
    



    Web Forms Developer:- That's convention over configuration. I'll take some time in understanding. It's somewhat tricky but not impossible

    MVC Developer:- Yeah. Now you are getting MVC. Obviously it is not impossible. But apart from my explanation try learning articles and books as much as you can. That'll help in understanding

    Webforms Developer:-Sure.

    I think this explanation of files is enough to give it an insight of how an MVC application is structured.

    Let's get to other files.

    Favicon.ico:- Your favicon file. I am sure you're aware about it.

    Global.asax:- It is known as the Asp.net application file and it contains the code for Application level events. So we should open it and take a look at it.
    We've got one method here
    Application_Start()
    and if you look closely in method body,we get some familiar names. Ever wondered how those files from App_Start folder get called? Now you have the answer . These methods are called here. The first method called for registering Area is a large concept in itself and will be there in subsequent articles.
    For now you can get the Areas as they allow us to organize models, views, and controllers into separate functional sections of the application, such as administration, billing, customer support, and so on.

    You can define other methods in global.asax as per your requirement. Like:
    Application_End(),Session_Start() and many more

    You can get a list and details about this in following link:
    http://www.dotnetcurry.com/showarticle.aspx?ID=126

    packages.config:-This file is managed by the NuGet infrastructure. It's used to track installed packages with their respective versions.

    Startup.cs-This file references to Open Web Interface for .NET (OWIN). OWIN is a specification on how web servers and web applications should be built in order to decouple one from another and allow movement of ASP.NET applications to environments . Please go through the link provided for more details as defining OWIN is out of the scope of this article. That'll be included in subsequent articles for sure. http://owin.org/

    Web.Config:-I am not gonna tell about it.;-)

    This is a long article on MVC project architecture. But still this is an article,not a book or documentation. So don't understand it as a final documentation of MVC and take references from MSDN or anywhere and try going in depth of any topic or file in this article.
    Thank You.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: