Thursday, June 13, 2013

How can we navigate from one view to other view using hyperlink?

By using “ActionLink” method (in Razor) as shown  in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GoHome” action.

@Html.ActionLink("Home","Gohome")

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 any user types “http://localhost/View/ViewCustomer/”,  it goes to the  “Customer” Controller  and invokes “DisplayCustomer” action.  This is defined by adding an entry in to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the URL structure and mapping with controller and action is defined.

sample routing in Global.asax:

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

complete flow of MVC

  • All end user requests are first sent to the routing in global.asax
  • Then All requests are sent to the controller.
  • The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
  • The final view is then attached with the model data and sent as a response to the end user on the browser.

what is the advantage of MVC instead of WebForms


MVC allows the user to write less amount of code to build the web applications as lots of components are integrated to provide the flexibility in the program.

The application tasks are separated into components to make it easier for the programmers to write the applications but at the same time the amount of the code also increases. 

Main focus remains on the testability and maintainability of the projects that is being carried out in large projects. 

Tuesday, June 4, 2013

Controller in MVC4 sample and explanation

To create an empty controller, right-click on the Controllers folder and select Add → Controller…,
entering the name HomeController.
The wizard will ask you if you’d like it to generate Create, Update, Delete, and Details actions for you. We won’t use those actions in this book, but feel free to let the wizard generate them for you if you’re interested to see what they look like. The wizard will create a new class file with one action named Index:

using System.Web.Mvc;
namespace MvcRazorBlog.Controllers
{
     public class HomeController : Controller
    {
         public ActionResult Index()
        {
            return View();
        }
    }
}

According to ASP.NET MVC’s default routes, the HomeController’s Index action handles requests for the site’s home page (the root of the site without specifying any file or folder names).
So, the next step is to reproduce the same data access logic that the Default.cshtml page uses to retrieve Post data.

Model in MVC sample and explanation


       
        ASP.NET MVC’s architecture dictates that the Model and the View are two separate entities, so in order to demonstrate the Razor syntax within ASP.NET MVC’s Razor View Engine, you should create a model that can hold and manage the site’s data. Since you’ve already implemented the blog site once, you already know what data the site uses. To create the Model for the ASP.NET MVC blog site, add a new class named Post to the website’s Models folder, with the following code:

namespace MvcRazorBlog.Models
{
 public class Post
 {
      public long ID { get; set; }
      public string Title { get; set; }
      public string Body { get; set; }
 }
}

Since the blog site doesn’t require very complex data, the Post class is all that’s needed at this point. Once it’s in place, you can create the Controller that will populate the Post class with data from the database and pass it to the View.

The Model-View-Controller Architecture


The MVC architecture comprises three layers, each with unique and independent responsibilities:

Model
       Represents the core business/domain data and logic, typically with POCOs (Plain Old CLR Objects), devoid of technology-specific implementations

View
       Responsible for transforming a Model or Models into a response sent to the user (typically HTML)

Controller 
       Interprets incoming web requests, managing the interaction between the user and the model (typically through database queries, web services calls, etc.) and building a Model for the View to consume
   
       In the course of an ASP.NET MVC website request, the platform locates and executes the  corresponding controller method, also called the action. The result of this action is almost always an ActionResult. The most widely used type is the ViewResult—an ActionResult indicating which view the framework should respond to the request with. Following ASP.NET MVC’s strict separation of concerns, it is not the controller that is responsible for rendering HTML. Instead, the ASP.NET MVC framework passes the ActionResult from the controller to the View Engine, which handles the conversion of a ViewResult into rendered HTML to send back to the client.

Razor helpers Vs Partial views

Razor Helpers
A Razor Helper is defined as a function with a specific set of input parameters that outputs rendered markup. Razor Helpers are most suitable for helping customize small sections of markup with minimal logic, such as an anchor tag or image tag. Since they typically contain less application-specific logic, they can often be used not only across views within the same project but also shared between applications. Think of Razor
Helpers as templates or “macros” that make your code easier to read, write, and maintain.

Partial Views
Whereas Razor Helpers are best suited for small, generalized sections of markup, partial views are best for breaking up larger views into more manageable pieces. These pieces typically contain more application-specific markup and logic. Though partial views can be reused across views in a project, the application-specific logic present in most views generally precludes sharing across applications. Conversely, just because it is possible to reuse a partial view in more than one place doesn’t mean you have to. Partial views can be a very effective tool for simplifying a larger view or isolating a particularly complex section of a page. Do not shy away from creating a partial view because it will only be used in one place—not only is that OK,
it’s sometimes very helpful!

Monday, June 3, 2013

what is Partial views in razor .....

Layouts and sections are a powerful and effective technique for creating maintainable websites because they provide the ability to split a given web page into smaller, more focused parts. In addition to layouts and sections, Razor offers yet another compartmentalization technique called partial views, which are self-contained portions of markup that can be reused throughout the website. Partial views are also useful for
separating complex or lengthy portions of markup from a page, making them easier to read and understand (and by extension, easier to maintain).

rendering order in nested layout ....

1. Content view
2. Nested layout
3. Wrapper (main) layout
Previous sections demonstrated that Razor views that leverage layouts render the content view first, followed by the layout (which injects the output from the content view).Since nested layouts effectively act as both layouts and content views, they simply add another layer to the mix. Thus, the requested content view is rendered first, which passes its output to the nested layout, which subsequently wraps the original content
view with itself, and then passes its output to the final main layout.

The Layout Rendering Life Cycle in Razor ....


<!DOCTYPE html>
        <html lang="en">
            <head>
                 <meta charset="utf-8" />
                 <title>@View.Title</title>
           </head>
        <body>
                  <div class="header">
                      @RenderSection("Header")
                 </div>
                        @RenderBody()
                <div class="footer">
                      @RenderSection("Footer")
                </div>
       </body>
       </html>

for above sample razor page life cycle event shown in below

1. _Layout.cshtml
2. The Header section in Post.cshtml
3. _Layout.cshtml
4. The body of Post.cshtml
5. _Layout.cshtml
6. The Footer section in Post.cshtml
7. _Layout.cshtml

Nested Layout and sections in Razor ....

A nested layout is any layout that refers to another, outer layout. This approach is useful when a subset of pages require the same markup, as is often the case when certain sections of a website need to appear slightly different from the others, yet retain the same general look and feel.

The first step to applying a nested layout to the Add Post page is to remove everything but its core content (everything inside the <body> tag). After this, use the same syntax as earlier examples to associate the page
with a layout, only instead of the _Layout.cshtml layout specify another (not yet created) layout file named ~/_AdminLayout.cshtml. The first few lines of the modified page are

shown below:
@{
 Layout = "~/_AdminLayout.cshtml";
 var title = Request["Title"];
 var summary = Request["Summary"];
 var body = Request["Body"];
 ...
}

Now it’s time to create the aforementioned _AdminLayout.cshtml layout. To do so, add a new CSHTML file named _AdminLayout.cshtml to the root of the website (follow the same steps used previously to create a new layout file). Then, completely clear the default template text, so that the file is empty, and replace with a reference to the _Layout.cshtml layout file as well as a call to the RenderBody() method. The following
snippet shows the full implementation of a nested layout: a Razor template that contains a call to the RenderBody() method and refers to another layout:

@{ Layout = "_Layout.cshtml"; }
@RenderBody()

if you attempt to execute the site with only this code in place, you will quickly find out that the original layout—_Layout.cshtml—is not satisfied: _AdminLayout.cshtml does not implement the required Header section!

a content view can define Razor sections that the view’s layout can access and execute. These section definitions, however, are only accessible to the immediate layout and vice-versa. In the case of the Add Post → Admin Layout → Main Site Layout scenario, this means that only the admin layout can access any sections defined in the Add Post content view. The main site layout cannot interact with the Add Post
content view at all! Conversely, the admin layout is responsible for implementing the required sections that the main site layout expects—it must explicitly implement these sections and cannot simply pass this responsibility to the Add Post content view.


how to find section is defined or not .....

Razor also provides another helpful method—IsSectionDefined()—which determines whether a section of a given name is defined in the content view. This information allows the layout not only to control the placement of the section’s content but also to affect other areas of the page.

in _layout page

@if(IsSectionDefined("Footer")) {
     <div class="footer">
          @RenderSection("Footer", required: false)
    </div>
 }

With this check in place, the footer div will only be rendered when the content view defines a Footer section. Otherwise, nothing will be rendered!

how to set @rendersection as required

The RenderSection() call includes an additional parameter—"required"—indicating whether or not content pages following this layout are required to explicitly implement a given section. This value is true by default (indicating that content pages are required to implement a given section); however, if this value is false, content pages can feel free to ignore that the section is defined, providing content for the optional section only when prudent.


sample   :  @RenderSection("sectionName", required: false)

Razor layout file sample and explanation

Take a look at a typical Razor layout file (_Layout.cshtml  or  _Layout.vbhtml):
<!DOCTYPE html>
        <html lang="en">
            <head>
                 <meta charset="utf-8" />
                 <title>@View.Title</title>
           </head>
        <body>
                  <div class="header">
                      @RenderSection("Header")
                 </div>
                        @RenderBody()
                <div class="footer">
                      @RenderSection("Footer")
                </div>
       </body>
       </html>


The layout file contains the main HTML content, defining the HTML structure for the entire site. The layout relies on variables (such as @View.Title) and special functions like @RenderSection([Section Name]) and @RenderBody() to interact with individual pages.
Once a Razor layout is defined, pages reference the layout and supply content for the sections defined within the layout. The following is a basic content page that refers to the previously defined _Layout.cshtml file:

@{ Layout = "~/_Layout.cshtml"; }
@section Header {
 <h1>My Blog<h1>
}
@section Footer {
 Copyright 2011
}
<div class="main">
 This is the main content.
</div>
rendered output (in HTML) shown in above figure 

1 - @view.title valued as my blog
2-  @RenderSection("header") as <h1>my blog</h1>
3 - @RenderBody as <div class="main"> This is the main content.</div>
4 - @RenderSection("Footer") as  Copyright 2011

Monday, May 27, 2013

In Razor block

The <text> block is an alternative to the @ character sequence that allows you to denote that an entire portion of a template is content. <text> is useful in scenarios where multiple lines of markup can be interpreted as code or text, such as:

 @if(!User.IsAuthenticated)
{  
 <text>    Guests are not allowed to view this content.    Please @Html.ActionLink("login", "Login") to view.    </text> }

which produces the following output when the user is not authenticated:    Guests are not allowed to view this content.    Please <a href="/Login">login</a> to view. As you can see, the opening and closing <text> tags are only used within the template to mark the beginning and end of the block of content and are not rendered along with the content. The example also shows that code statements are still perfectly acceptable within a <text> block. 

How Razor Parses Markup and Code?

            The @ symbol is the heart of the Razor syntax, the character that Razor uses to differ- entiate code from markup. The @ symbol marks a point at which the developer intends to switch from markup to code. In simple cases, no additional characters are needed to indicate when the code stops and the markup resumes. Razor’s intelligent parser determines which parts of the template are code and which are markup.
What makes a valid code statement? 
            Razor uses the following algorithm to find the end of a code statement once it reads the @ symbol trigger:
1. Read to the end of a valid identifier (i.e., a C# or VB keyword) or variable name.
2. If the next character is an opening bracket ( ( or [ )… a. Keep parsing until the corresponding closing bracket is located. Nested brack- ets are also tracked to avoid premature closing of a block. b. Loop back to #2.
3. If the next character is a . (period) and precedes a valid identifier, jump to #1.
 4. Complete the code statement and continue processing the rest of the markup. Razor relies on the current language’s syntax to determine the end of a code statement. Razor also attempts to “read forward,” checking if the upcoming content resembles code or markup.
 The specifics depend on the language currently in use (C# or VB).

Here’s a typical Razor snippet:
@foreach(var item in order.Items) 
{   
 <li>@item.Name</li>
}

The first line initializes the loop variables and opens the loop with an opening bracket; the second line renders markup; and the third line contains the closing bracket to end the loop. There is a clear transition between code and markup because the second line begins with an <li> tag that is clearly an HTML element and the third line is clearly the foreach loop’s closing tag. 

Code Blocks in razor

             A code block is a section of the view that contains strictly code rather than a combi- nation of markup and code. Razor defines a code block as any section of a Razor template wrapped in @{ } characters.
            The @{ characters mark the beginning of the block, followed by any number of lines of code. The } character closes the code block. Keep in mind that the code within a code block is not like code in a code nugget. It is fully-formed code that must follow the rules of the current language; for example, each line of code written in C# must include a semicolon (;) at the end, just as if it lived within a class in a .cs file.

Here is an example of a typical code block:

@{
LayoutPage = "~/Views/Shared/_Layout.cshtml";
View.Title = "Product Details for " + Model.ProductName;
 } 

          Code blocks do not render anything to the page. Instead, they allow you to write ar- bitrary code that requires no return value. Variables defined within code blocks may be used by code nuggets in the same scope. That is, variables defined within the scope of a foreach loop or similar container will only be accessible within that container.

Code Nuggets

              Code nuggets are simple expressions that are evaluated and rendered inline. They can be mixed with text and look like this:

                         Not Logged In: @Html.ActionLink("Login", "Login")

              The expression begins immediately after the @ symbol, and Razor is smart enough to know that the closing parenthesis indicates the end of this particular statement. The previous example will render this output:        
                     
                        Not Logged In: <a href="/Login">Login</a>

              Notice that code nuggets must always return markup for the view to render. If you write a code nugget that does not return anything (i.e. returns void), you will receive an error when the view executes.

What is Razor Syntax? What new in Razor....

Razor is a template syntax that allows you to combine code and content in a fluid and expressive manner. Though it introduces a few symbols and keywords, Razor is not a new language. Instead, Razor lets you write code using languages you probably already know, such as C# or Visual Basic .NET.