Monday, November 24, 2014

Can we overload MVC controller action methods? (MVC Polymorphism)

This Saturday and Sunday when i was taking MVC class in Mumbai one of the participants asked this weird question, Can we overload MVC action methods?. This question was asked to him during a MVC interview recently.

For moment I wondered why interviewer such kind of questions which does not test anything about programmer's ability. But let's leave that argument from some other day and lets answer this question.

Well the answer is YES and NO depending on your expectation. Now before you turn me in to a politician who answers from both side's let me explain you why i have given such kind of a dubious answer.

Overloading or in other words polymorphism is a feature of object oriented programming. So if you have some kind of a below controller code which has methods overloaded with same name and different argument's it would compile very well.
public class CustomerController : Controller
    {
        //
        // GET: /Customer/

publicActionResultLoadCustomer()
        {
return Content("LoadCustomer");
        }
publicActionResultLoadCustomer(string str)
        {
return Content("LoadCustomer with a string");
        }
    }
But now if you are thinking that when you call "http://localhost:3450/Customer/LoadCustomer/" it should invoke "LoadCustomer" and when you call "http://localhost:3450/Customer/LoadCustomer/test" it should invoke "LoadCustomer(string str)" you are WRONG.

If you try to this you will end with a below error. Read the word "Ambiguous" in the error , does something click. Ok , let me explain in more detail what the below error means.










Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism it works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.

And i know if you answer with the above argument MVC interviewer would still press that he wants to implement polymorphism , so how do we go about doing it.

If you wish to keep polymorphism and also want the HTTP request to work you can decorate one of the methods with "ActionName" as shown in the below code.
public class CustomerController : Controller
    {
        //
        // GET: /Customer/

publicActionResultLoadCustomer()
        {
return Content("LoadCustomer");
        }

        [ActionName("LoadCustomerbyName")]
publicActionResultLoadCustomer(string str)
        {
return Content("LoadCustomer with a string");
        }
    }
So now you can invoke with URL structure "Customer/LoadCustomer" the "LoadCustomer" action and with URL structure "Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be invoked.























In case you want to start learning MVC , below is a nice MVC step by step video series which will help you to learn MVC in 16 hours i.e. 2 day's. Give a try.



Friday, October 31, 2014

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

So you have hit this blog note because you are confused about the difference between “ViewResult” and “ActionResult” and I hope that your confusion ends here.

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
Are you struggling to learn ASP.NET MVC start with the below video




Sunday, September 14, 2014

MVC Tempdata , Peek and Keep confusion

This blog assumes you have idea on MVC in case not I would suggest starting from thisyoutube video Learn MVC.

Recently I was taking MVC class in Mumbai and I saw there was lot of confusion among participantson how MVC tempdata , Peek and Keep works. I think the confusion stems because most of the MVC developers know only thehalf truth.

So the half thing which most of MVC developer know is:-

“Tempdata helps to preserve values for a single request”.

The other half-truth which developers do not know is or I will say which confuses developer is:-

“TempData CAN ALSO preserve values for the next request depending on 4 conditions”.

So let us try to understand the above two statements. When an end user send’s a request to a MVC application “TempData” is maintained throughout the complete request. This request can traverse through multiple actions or controllers until it displays the view on the browser.


Now in the same session (without closing the browser) if a new / second request is initiated then “TempData” will be persisted depending on 4 CONDITIONS:-

  • Not Read.
  • Normal Read.
  • Read and Keep.
  • Peek and Read.


So let’s discuss these four conditions in more detail ( Do see the below diagram for better understanding ):-

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2  ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

stringstr = TempData[“MyData”];

Even if you are displaying it’s a normal read like the code below.

@TempData[“MyData”];

Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.

@TempData[“MyData”];
TempData.Keep(“MyData”);

Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

stringstr = TempData.Peek("Td").ToString();


So if you register these four condition’s in your mind you should not have any confusion’s around TempData:) .

Saturday, August 16, 2014

Things you will miss in ASP.NET MVC as an ASP.NET Webform developer

Introduction

No CodeBehind

No Server controls

No Page life cycle

No ViewState


Introduction


I have been a great fan of ASP.NET Webform development but for past 2 years ASP.NET MVC is the talk of the town. If you are new to MVC start here and if you want to learn MVC super-fast start here.

Note: - If ASP.NET MVC and ASP.NET WebForm vocabulary is confusing please read this before moving ahead :-http://computerauthor.blogspot.in/2014/08/aspnet-vs-mvc-vocabulary-confusion_15.html.

When I started ASP.NET MVC development it took lot of time as an ASP.NET webform developer to get adjusted and acquainted with ASP.NET MVC development thought. This article walks you through some important mind set changes you need to make when working with ASP.NET MVC.

 

No CodeBehind


The whole thought of MVC is to get rid of behind code. Because behind code is not reusable , not testable .So when you add a view / UI in MVC is you will be find no behind code. You will find “.ASPX” but there is no “ASPX.CS”. You will find CSHTML but there is no CSHTML.CS.


Now the time we say “No Behind code” this has a cascading effect. The remaining points are the after effect of “No code behind” concept.

No Server controls


ASP.NET webform Server controls was always a life savior. It was like a magic where you drag and drop and you are done.Now because we do not have any behind code server controls will not be seen in your tool box. You have to use HTML to create your MVC UI. The maximum support officially you have currently is HTML Helper classes , you can read about it from here.


You can use server controls on an ASPX view but it’s not advisable as it will generate inline code behind again defeating the purpose of MVC.

No Page life cycle


Because we do not have behind code there is no such thing as page life cycle in ASP.NETMVC.In ASP.NET Webform the first hit comes to the Page and then rest of the things happen. ASP.NET Webform is UI first approach while MVC is class first approach.

In MVC the first hit comes to the controller class and then to the UI. So all the logic of page life cycle goes in the controller.So no more discussion on page life cycle and which event what code needs to be written.

No ViewState


There are no automated generated hidden fields like viewstate. We have more robust and fine tuned way of session management viewdata , tempdata ,viewbag and session variables. You can read more about them from clicking here.

Want to Learn MVC in 2 days start from this video






Friday, August 15, 2014

ASP.NET VS MVC – Vocabulary confusion

If you have clicked on this article thinking that ASP.NET is the old thing and MVC is the new thing then you need to seriously read this article.


Recently I was taking Learn MVC in 2 days in Andheri Mumbai and I saw lot of participants thinking ASP.NET is different and MVC is different. During the MVC training many were referring ASP.NET as the old thing and MVC as the new thing. But actually they are one and the same thing.

ASP.NET is a web framework of Microsoft and MVC is a visual studio code template to  write code using MVC architecture style. The proper name of OLD ASP.NET is “ASP.NET webforms”. So ASP.NET webform is the old ASP.NET with behind code and MVC is the new thing.


This is also very much evident when you create an ASP.NET Web project using visual studio. In visual studio you will see two different templates one with the name “ASP.NET Webform” and the other with “ASP.NET MVC”.


Note :- Web and Webform are one and the same thing.

If you want to learn MVC step by step start from the below link

http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in

Tuesday, July 8, 2014

What is CodeLens?

Code lens is a new feature in visual studio 2013 which helps us to understand three important things about our code while we are coding inside visual studio.

All these three things(Impact, test and latest) are seen right above your class / method when you code in visual studio as shown in the below figure.


Impact: - First thing code lens shows is when we change the code what isthe impact of those changes. For instancein the above figure you can see it stating that if you make any changes to the log method it will be impact 1 reference.

If you click on references further it will also show which the classes it’s referencing. With this we come to know the level of impact this change will have further.

In the below screen it’s stating that “ConsoleApplication2” and “UnitTest1.cs” are the classes which.


If you further click on “Show on Code Map” menu you should see a graphical representation of dependencies.


Test :- Second important thing code lens tells is whether this method was unit tested or not.  For instance you can see it say’s 1 passing means this method was unit tested.


Latest: -Third thing it tells where this is a latest code or not. You can see the last menu which states this is not a latest code and you need to do a get latest from the server.

But now for the bad news nothing is free, code lens is currently available only in ultimate edition. Wish it was free as air….. ;-)


Below is a nice and short video of codelens created by www.questpond.com team.