Wednesday, 20 May 2015

View in Asp.net MVC

Here we will discuss View in MVC with an example , As we discuss before that View in MVC is used to show the data to user.
Step(1) :- Go to your application and right click on Controller and add a new controller and give name it as “HomeController” and give Scaffolding option as Empty MVC Controller, And click ADD.
After Click add there is Default Function name is “index” with return type is “ Action result” will be available.

Step(2) :- Now here we want to display list of courses available in IT filed. So for that we have to change the return type of this Index Method As List of String because Courses will be in String format. So let’s change the return type of this method.
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public List<string> Index()
        {
            return new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
        }

    }
}


We can assess these courses name from database but here we are doing as hardcoded.
  Step(3):-  At  this point if we run our application we will see output as not expected means it will not shoe the name of courses “System.Collections.Generic.List`1[System.String]”  for showing the output as we want we have to add the view to our application
The purpose of view to render the data or format of data as end user wants , in view we can change the format of data means if we want data as bold , colour we can do. So the work of view is to present the data to the end user .
Step(4): Now add a view for this method , so right click on index function add a view

After click on Add view you will see a view window there you will see that the view name is same as Controller name and View engine as Razor Engine after click on ADD. Then you will see a View in View Folder of your application.

If we see that where this Index View add then go to solution explore in View folder there is another folder as HOME and then you will your Index View. Actually here why is view is under home folder because this View is for Home Controller method  , So all the view which are related to this home controller will come under this home Folder.
Step(5):- Now we have to change the return type of this index method which exists in Home controller for showing result in home controller. Now return type will be “Action result”
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
            return View();
        }

    }
}



Here it return a view but how it will find a Index View for that while executing application it will go to View folder and there it will see Home Folder (because Controller name is home) then it will find a View name as Index(Because controller method name is Index).
Step(6): Now here we want list of Courses for showing list of courses here need to pass Courses list from Controller to View . There are several method for passing data from controller to view.
We can use ViewData, View Bag or View modal. Here for passing the data from Controoler to view we will use ViewBag, Means we have to store this information to a property so here we will store this courses information into ViewBag.Courses(Here Courses is any meaningful name) .
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Courses = new List<string>()
    {
        "COMPUTER SCIENCE",
        "DOT NET",
        "C++",
        "INFORMATION TECHNOLOGY"
    };
            return View();
        }

    }
}


Step(7) :- So now for showing list of Coruses we have to change in Index.csHtml class go to Index.csHtml class and give the title name.
For showing the data in list we have to make the foreach loop using the HTML helper  for getting this HTML Helper control start with “@” symbol.
This  "@" symbol is used to switch b/w  html and c# code
@{
    ViewBag.Title = "Courses Name";
}

<h2>Courses Name</h2>
<ul>

@foreach (string Courses in ViewBag.Courses)
{
    <li>@Courses</li>
}

</ul>


Now Run your application and you will see the courses name as List.

Here if we see the return type of view is ViewResult but we wrote index method with ActionResult return type that because if you will go to definition of this view you will see that this ViewResult is inherited from the ActionResult.

Note:- For Passing the data from Controller to View , we should use Strongly type View modal instead of using ViewData And ViewBag.

Difference Between ViewResult and ActionResult in MVC.

Here we will understand difference between View Result and Action result.  Basically Action result is an abstract class which has subtypes and the View result class is derived from Action Result class.
“View Result” is derived from Action Result , so Action Result in MVC is an abstract parent class



See the below code
public ActionResult Index()
{
      return View(); 
}


In the above code we can see that it is returning a “View Result” object and cause of polymorphism this “View Result” object automatically types casted for the parent class means “Action result”.
 Action Result Subtypes:-
  • ViewResult - Renders a specified view to the response stream
  • PartialViewResult - Renders a particular partial view to the response stream
  • EmptyResult - An empty response is given.
  • RedirectResult - It Performs an HTTP redirect to a specified URL
  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is decide by the routing engine, based on given data from route.
  • JsonResult - Serializes a given View Data object to JSON format
  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  • ContentResult - its Write content to response stream without need of a view
  • FileContentResult - Returns a file to the client
  • FileStreamResult - it Returns a file to the user, that is provided through a  Stream
  • FilePathResult - it Returns a file to the user




ASP.Net MVC Routing With Example

Here we will learn Asp.net MVC Routing with an example. Routing is a process of mapping the controller and action method through which a view is use for user as an output. Basically Routing work for an URL or we it is a  Restful URL.
This URL is understand at the Run time means when controller loads and execute action method then t decide URL or view that which screen have to show to user. Whenever a user make a request related to page then it load the page then it transfer this page request to the user’s browser via all the page life cycle. Here .aspx page and .aspx.cs page both are bind with this so when it render user request then this asp.net MVC load both the pages.
Here we will understand Asp.net MVC Segment, ASP.Net MVC 3 type of Segment 
  1. Controller Segment 
  2. Action Segment
  3. Parameter Segment 
In your application app_start folder you will see a class as “RouteConfig.cs” class contain a function as ” RegisterRoutes” Right click on this and go to this definition .
RouteConfig.cs method
 protected void Application_Start() 
      { 
          AreaRegistration.RegisterAllAreas(); 
 
          WebApiConfig.Register(GlobalConfiguration.Configuration); 
          FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
          RouteConfig.RegisterRoutes(RouteTable.Routes); 
          BundleConfig.RegisterBundles(BundleTable.Bundles); 
      }


When you will go on this method this will go to Register
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;


namespace MvcApplication

{

    public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = " Home ", action = "Index", id = UrlParameter.Optional }
            );

        }

    }

}

     Here it contain default controller as Home and action as Index and here parameter as optional you can change all these thing means you can call your method which is created in your controller , you also can change your controller as I did in  “Controller in MVC application” tutorial.
Controller Segment : -  Controller is basically a view name that is used to show the data  to the user , it is used to handling user request and response. We can create our controller , these controller are stored in Controller class , for example we create HomeController.cs. All the controller are inherited from the base controller class.
This home controller class contain two type  controls As index and about
using System.Web.Mvc;

namespace MVCController
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

public ActionResult About()
{
return View();
}
}
}

Action Segment : - You can follow this link for this  “Action Result and action method”
Parameter Segment : - you can follow this link “Controller in MVC
Asp.net MVC Routing : -  Routing is the most important feature of Asp.net MVC , because this the modal which is responsible for mapping for user request and for response to specific controller and method.
This routing data is filled in Application_start event (means this method contain “.RegisterRoutes(RouteTable.Routes);  “ )  it uses Route table object for filling the data,
Route engine is used to matching the incoming request and execute action method.

Customizing Routing in ASP.NET MVC :-  we are able  customize our default route of execution. Mostly all the MVC application use default route for execution but sometimes we need to customizing  this default route. There are some example for customize route,
If URL is date then we need specific format like 11-05-2015   , if url contain integer ID then we need to customize this.
Attribute Routing : -  This is a new type of Routing which is introduced  in Asp.net MVC 5. Attribute routing uses attributes for creating Routes. Basically Attribute routing gives us more control for handling URL by adding routes directly to controller and actions
This Routing should be register in “RegisterRoutes” method of Global.asax or in RoutCnfig.cs file. This routing should be configures before the convention based routing
This following code shows us that  how to register a Attribute Routing
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //Add the following line
        routes.MapMvcAttributeRoutes();  
        //convention based routes
    }
}
If we are using both Attribute routing and convention based routing then actions which are configured for attribute routing will work as per attribute routes and the actions which are not configured will work as convention based routes.
Routing Constraints : - Routing constrains allow us to use validation on the define route. Routing constrains enable user to prevent for getting route map with the user request unless specific validation matched.
Ex user request should be matched with particular route only if ID is parameter and the type is int.
Following is the code for defining creates routes with the constraints which allow us to integer value as ID Parameters.
routes.MapRoute("Default", // Route name
    "{controller}/{action}/{id}", // Route Pattern
    new { controller = "Orders", action = "GetOrder",
            id = UrlParameter.Optional }, // Default values for parameters
    new { id = @"\d+" } //Restriction for id
    );
If we need more complex validation, we can implement "IRouteConstraint" interface and  use Match method to implement logic.
follwoing code creates a  custom route constraints by implementing "IrouteConstraint". that checks whether provided parameter is valid  or not.
public class DateConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, 
        string parameterName, RouteValueDictionary values,
                 RouteDirection routeDirection)
    {
        DateTime dt;
 
        return DateTime.TryParseExact(values[parameterName].ToString(), 
        "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
    }
}
Area Registration : -
Area is a feature of MVC2. this allows us  to create our applications in bgood way. Ex  we have billing application we may have different parts like Billing, Admin, , Order and so on. We  will create different Area for each and every part. Every area will contain Views.
we can register specific area by inherting "AreaRegistration" class
following code shows us that  how to register Admin Area.
public class HelpDeskAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        { 
            return "Admin";
        }
    }
}
  
public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "admin_default",
        "admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}
            






Install MVC and Check current MVC version in application

Here we will teach how to create first Asp.Net MVC application.Before that we will learn how to install MVC in our window
 Install asp.net mvc
Before install any version of MVC first we will see which version exist in our window for getting this go to control panel and when we will click on "Programs and Features" initially  here MVC2 will be installed by default.


Now we want to install MVC3 and MVC4 for that go to following link and download then install.
After Successfully installation it will show all MVC installation.


 Get which MVC version we are using in application.
There 2 type of ways for getting this thing. We can achieve this by design and with runtime using coding.
Design Time :- Go to your application , solution explorer expand your reference folder and see System.Web.Mvc assembly  and then right click on this reference  and select Properties and in property window at last you will see current version.

At Runtime using code: - Go to your application and you will see there home controller there you write following code  in ”index method” 
typeof(Controller).Assembly.GetName().Version.ToString() 

Now run your application and then on browser you will see your current MVC version



C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...