Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Tuesday, July 12, 2016

TempData , Peek and Keep ASP.NET MVC

 What is need of "TempData" ?

TempData helps to preserve data throughout the current request. The request can travel through action to action or controller to controller until the view is displayed.

What is difference between TempData and ViewData ?

"TempData" maintains data for the complete request while "ViewData" maintains data only from Controller to the view.

Does "TempData" preserve data in the next request also?

"TempData" is available through out for the current request and in the subsequent request it's available depending on whether "TempData" is read or not.

So if "TempData" is once read it will not be available in the subsequent request.

What is the use of Keep and Peek in "TempData"?

Once "TempData" is read in the current request it's not available in the subsequent request. If we want "TempData" to be read and also available in the subsequent request then after reading we need to call "Keep" method as shown in the code below.

@TempData["MyData"];
TempData.Keep("MyData");

The more shortcut way of achieving the same is by using "Peek". This function helps to read as well advices MVC to maintain "TempData" for the subsequent request.

string str = TempData.Peek("Td").ToString();

Difference between Html.EditorFor and Html.TextboxFor in ASP.NET MVC

If you are working on Web Application development using ASP.NET MVC, you would come across the Html.EditorFor and Html.TextboxFor in the Razor View.
The EditorFor is a kind of smart helper method. This will render the control based on the type in the model. For example, assume that you have a Boolean field in the model bind to the EditorFor. This will render checkbox.

Html.EditorFor

@Html.EditorFor(model => model.LastName)
This HTML helper method is very dynamic in nature. Based on which type of data is passed to this method, the output changes.

For example,
1. if model property type is of string type, it renders a textbox
2. if the property type is boolean type it renders a checkbox.
3. if the property type is of integer type, it render input type="number" textbox.

In order to control the output of the Html.EditorFor we can use EditorTemplates for different data types.

Html.TextBoxFor
@Html.TextBoxFor(model => model.LastName)
This HTML helper method only renders a TextBox as output irrespective of whatever data type the model property is of.