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.



Thursday, June 12, 2014

Explain MVC model binders ? ( ASP.NET MVC interview questions)

Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model.



Take the below simple HTML form example :-








Now this form needs to fill the below “Customer” class model. If you see the HTML control name they are different from the class property name. For example HTML textbox control name is “CCode” and the class property name is “CustomerCode”.  This mapping code is written in HTML binder classes.

publicclassCustomer
{
publicstring CustomerCode { get; set; }
publicstring CustomerName { get; set; }
}

To create a model binder we need to implement “IModelBinder” interface and mapping code needs to be written in the “BindModel” method as shown in the below code.

publicclassCustomerBinder : IModelBinder
{

publicobject BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;

string strCustomerCode = request.Form.Get("CCode");
string strCustomerName = request.Form.Get("CName");

returnnewCustomer
            {
                CustomerCode = strCustomerCode,
                CustomerName = strCustomerName
            };
}
}

Now in the action result method we need to use the “ModelBinder” attribute which will attach the binder with the class model.

publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj)        
{

return View(“DisplayCustomer”);
}

This MVC interview question was provided by questpond which conducts ASP.NET MVC training . In case you are new to MVC you can start from questpond video which is shown below.

Monday, May 19, 2014

Server.Transfer” VS “Response.Redirect” – Simplified

Introduction

“Server.Transfer”vs “response.Redirect”

So when to use “Server.Transfer” and when to use “Response.Redirect” ?

What is importance of “preserveForm” flag in “Server.Transfer”?

Response.Redirect(URL,true) vsResponse.Redirect(URL,false) ?

Introduction


In ASP.NET some of the concepts do the same task but are meant to be used in different scenarios. One such concept which is confusing and most discussed among developers is the difference between “Server.Transfer” and “Response.Redirect”.



“response.redirect” and “server.transfer” helps to transfer user from one page to other page while the page is executing. But the way they do this transfer / redirect is very different.

In this short blog we will discuss about how they differ and in which scenarios we should use them.

In case you are visual guy and would like see demonstration rather than theory I would suggest to see the below facebook video which explains the difference in a more demonstrative way.



“Server.Transfer”vs “response.Redirect”


The main difference between them is who does the transfer. In “response.redirect” the transfer is done by the browser while in “server.transfer” it’s done by the server. Let us try to understand this statement in a more detail manner.

In “Server.Transfer” following is the sequence of how transfer happens:-
  1. User sends a request to an ASP.NET page. In the below figure the request is sent to “WebForm1” and we would like to navigate to “Webform2”.
  2. Server starts executing “Webform1” and the life cycle of the page starts. But before the complete life cycle of the page is completed “Server.transfer” happens to “WebForm2”.
  3. “Webform2” page object is created, full page life cycle is executed and output HTML response is then sent to the browser.



One important point to note here is the URL is not changed to the target page. If you have sent request from “Webform1.aspx” to redirect to “WebForm2.aspx” on the browser URL you will still see “WebForm1.aspx”.

While in “Response.Redirect” following is the sequence of events for navigation:-
  1. Client (browser) sends a request to a page. In the below figure the request is sent to “WebForm1” and we would like to navigate to “Webform2”.
  2. Life cycle of “Webform1” starts executing. But in between of the life cycle “Response.Redirect” happens.
  3. Now rather than server doing a redirect , he sends a HTTP 302 command to the browser. This command tells the browser that he has to initiate a GET request to “Webform2.aspx” page.
  4. Browser interprets the 302 command and sends a GET request for “Webform2.aspx”.

In this case you will the URL’s are changed as per redirection. So if you have redirected to “Webform2.aspx” then on the browser URL you should see “WebForm2.aspx”.

In other words “Server.Transfer” is executed by the server while “Response.Redirect” is executed by thr browser. “Response.Redirect” needs to two requests to do a redirect of the page.

So when to use “Server.Transfer” and when to use “Response.Redirect” ?


Use “Server.Transfer” when you want to navigate pages which reside on the same server, use “Response.Redirect” when you want to navigate between pages which resides on different server and domain.



Below goes the consolidated table with all the differences as discussed at the top.

Server.TransferResponse.Redirect
RedirectionRedirection is done by the server.Redirection is done by the browser client.
Browser URLDoes not change.Changes to the redirected target page.
When to useRedirect between pages of the same server.Redirect between pages on different server and domain.


What is importance of “preserveForm” flag in “Server.Transfer”?


“Server.Transfer” helps to redirect from one page to other page. If you wish to pass query string and form data of the first page to the target page during this redirection you need to set “preserveForm” to “true” as shown in the below code.

Server.Transfer("Webform2.aspx",true);

By default the value of “preserveForm” is “true”.

Response.Redirect(URL,true) vsResponse.Redirect(URL,false) ?


Response.Redirect(URL,false) :- Client is redirected to a new page and the current page on the server will keep processing ahead.

Response.Redirect(URL,true) :- Client is redirected to a new page but the processing of the current page is aborted.


Below is a facebook video whichdemonstrates practically the difference between server.transfervsresponse.redirect .A big thanks to www.questpond.com to allow me to publish this videos for free on facebook.