Wednesday 27 January 2016

ViewResult First Response

Represents a class that is used to render a view by using an IView instance that is returned by an IViewEngine object.

IView Interface

 


NameDescription
System_CAPS_pubmethodRender(ViewContext, TextWriter)
Renders the specified view context by using the specified the writer object.

IViewEngine Interface

 


NameDescription
System_CAPS_pubmethodFindPartialView(ControllerContext, String, Boolean)
Finds the specified partial view by using the specified controller context.
System_CAPS_pubmethodFindView(ControllerContext, String, String, Boolean)
Finds the specified view by using the specified controller context.
System_CAPS_pubmethodReleaseView(ControllerContext, IView)
Releases the specified view by using the specified controller context.

A view engine is called by the MVC framework to render view pages.

 


Introduction

This article shows how to use view result in a Controller in MVC.

Step 1

Create a MVC project from the "Empty" template.

Right-click on "Controllers" and select "Add" >> "Controller...".



Step 2

Select "MVC 5 Controller - Empty" to add an empty Controller.

Click on the "Add" button.



Step 3

Name the Controller as in the following:



Step 4

Now we need to create a view.

Right-click on "Index" and select "Add View...".



Step 5

Name the view and select "Empty (without model)" as the template.

Click on the "Add" button.



Step 6

Add a title in the index page.



Step 7

ViewResult represents a class that is used to render a view by using an IView instance that is returned by an IViewEngine object. View() creates an object that renders a view to the response.



Step 8
Now we need to create a view.

Right-click on "About" and select "Add View...".



Step 9

Name the view and select "Empty (without model)" as the template.

Click on the "Add" button.



Step 10

Add the title in the about page.



Step 11

Add html.actionlink for about.cshtml.



Step 12

Run the project, click on the about link and you will see the about page rendered in the browser.


Properties :: ---



NameDescription
System_CAPS_pubpropertyMasterName
Gets the name of the master view (such as a master page or template) to use when the view is rendered.
System_CAPS_pubpropertyModel
Gets the view data model.(Inherited from ViewResultBase.)
System_CAPS_pubpropertyTempData
Gets or sets the TempDataDictionary object for this result.(Inherited from ViewResultBase.)
System_CAPS_pubpropertyView
Gets or sets the IView object that is rendered to the response.(Inherited from ViewResultBase.)
System_CAPS_pubpropertyViewBag
Gets the view bag.(Inherited from ViewResultBase.)
System_CAPS_pubpropertyViewData
Gets or sets the view data ViewDataDictionary object for this result.(Inherited from ViewResultBase.)
System_CAPS_pubpropertyViewEngineCollection
Gets or sets the collection of view engines that are associated with this result.(Inherited from ViewResultBase.)
System_CAPS_pubpropertyViewName
Gets or sets the name of the view to render.(Inherited from ViewResultBase.)



NameDescription
System_CAPS_pubmethodEquals(Object)
(Inherited from Object.)
System_CAPS_pubmethodExecuteResult(ControllerContext)
When called by the action invoker, renders the view to the response.(Inherited from ViewResultBase.)
System_CAPS_protmethodFinalize()
(Inherited from Object.)
System_CAPS_protmethodFindView(ControllerContext)
Searches the registered view engines and returns the object that is used to render the view.(Overrides ViewResultBase.FindView(ControllerContext).)
System_CAPS_pubmethodGetHashCode()
(Inherited from Object.)
System_CAPS_pubmethodGetType()
(Inherited from Object.)
System_CAPS_protmethodMemberwiseClone()
(Inherited from Object.)
System_CAPS_pubmethodToString()
(Inherited from Object.)

how to call an Action from within another Action, and set a specific View, in an ASP.NET MVC web application




ActionResult" is an abstract class while "ViewResult" derives from "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 view dynamically "ActionResult" is the best thing. For example in the below code snippet you can see we have a simple action called as "DynamicView". Depending on the flag ("IsHtmlView") it will either return "ViewResult" or "JsonResult".







using System.Web.Mvc;
 
namespace Website.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            //// Code for this "Index" action can be written here.
 
            return View();
        }
 
        public ActionResult Index2()
        {
            var viewResult = Index() as ViewResult;
 
            if (viewResult != null)
            {
                viewResult.ViewName = "~/Views/MyFolder/MyPage.aspx";
            }
 
            //// Code specific to this "Index2" action can be written here.
 
            return viewResult;
        }
    }
}

Tuesday 26 January 2016

Difference Between ViewResult() and ActionResult() in MVC ?

Difference Between ViewResult() and ActionResult() in MVC ?

So without wasting time let’s get the difference in one sentence:-

“ActionResult is an abstract parent class from which ViewResult class has been derived”.


So when you see MVC controller and action codes as shownbelow :-
public ActionResult Index()
{
      return View(); // this is a view result class
}
The above code means that you are returning a “ViewResult” object and due to polymorphism this object is automatically type casted to the parent class type i.e “ActionResult”.

In case you are newbie to polymorphism , let’s do a quick revision. In polymorphism parent class object can point towards any one of its child class objects on runtime. For example in the below code snippet we have parent “Customer” class which is inherited by “GoldCustomer” and “SilverCustomer” class.

public class Customer
{}

public class GoldCustomer : Customer
{}

public class SilverCustomer : Customer
{}
 
So down the line later during runtime your parent “Customer” object can point to any one of the child object i.e “GoldCustomer” or “SilverCustomer”.
Customer obj = new Customer();
obj = new GoldCustomer();
obj = new SilverCustomer();
How does this polymorphism benefit for MVC results?

MVC applications are used to create web sites or web application. Web applications work in a request and response structure because they follow HTTP protocol.



So the end user using theUI sends a HTTP POST or a GET request and the web application depending on scenarios sends a response. Now the request is quiet standard but the response types differ due to different kind of devices.



For example if its a browser you expect HTMLresponse, if its jquery you expect JSON format or for some other client types you just want simple text contents and so on.

So what the MVC team did is they created a base general class called “ActionResult” which was further inherited to create different types of results.

So in the action result code you can pass some parameter from the UI and depending on this parameter you can send different response types. For instance in the below example we are passing a boolean flag whether it’s a HTML view or not and depending on the same we are streaming different views.
public ActionResult DynamicView(bool IsHtmlView)
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
}
 
 
Cool isn’t it rather than writing different methods for each response you just have one method with dynamic polymorphic response.


There are 11 different response types which can be sent to the end user :-
  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 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 is the relationship between TestController and Test?

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 Smile | :) , 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.
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.
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.
[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.
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.

Thursday 21 January 2016

Table To Xml in Sql Server

SELECT
          Filed1 ,
          Filed2 ,,
          Company_ID ,
          Employee_ID
FROM    dbo.TableName  WITH (NOLOCK)
FOR
XML PATH('Node') ,
ROOT('Root')

SqlDataBaseLibrary

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using AOS.Repository.Infrastructure; using S...