Banner Ad

Wednesday, October 12, 2016

ASP.Net MVC : TempData - A Closer Look

By Francis   Posted at   1:43 PM   TempData and ASP.Net MVC 1 comment
             
               

                As an ASP.Net MVC developer, you may frequently involved with these terms like Tempdata, viewdata and viewbag. In this post, I’m going to take a close look about TempData and how it works.

Read: ViewBag, ViewData and TempData

For explanation purpose, I’m going to create a small MVC project with 3 views and a controller.
  1. Index.cshtml – This is the default view, which is loaded by the default action method.
  2. Page1.cshtml
  3. Page2.cshtml
And the controller named as:
  1. DefaultController.cs 
TempData:

We will start with TempData. I will set the value of TempData in the Action method “Index”, like below:

using System.Web.Mvc;
namespace SessionHandlingInMVC.Controllers 
{ 
    public class 
DefaultController : Controller 
    { 
        // GET: Default         
public ActionResult Index() 
        {             
          TempData["MyTempDataValue"] = "Value initialized in Index Action Method"; 
          return View(); 
        } 
        
public ActionResult Page1() 
        { 
            return View("Page1"); 
        }
public ActionResult Page2() 
        { 
      return View("Page2"); 
        } 
    } 
}

In the “Index” view, we can get the value of the initialized “Tempdata” value as below:

<h2>Index Page</h2>
<p> 
   @{ 
       string strTempDataValue = 
(string)TempData["MyTempDataValue"]; 
    } 
    @strTempDataValue 
</p>

Please take a close look how the value is retrieved from the “TempData”.You can’t directly assigned to it the specific type.  A typecasting is needed, when you retrieved the value from Tempdata. The above snippet just get the value from TempData dictionary and print it on.

In the next snippet, I’m going to change the above snippet a little bit like below:

<h2>Index Page</h2> 
<p> 
   @{ 
       string 
strTempDataValue = (string)TempData["MyTempDataValue"]; 
    } 
@strTempDataValue
    @{ 
        string strAnotherRead = 
(string)TempData["MyTempDataValue"]; 
    } 
    @strAnotherRead 
</p>



In the above snippet, we have read the TempData value as twice. As a result the value also printed twice in the view.


The above result confirm that, you can read the TempData value inside the current request as much time as possible.

In the following snippet, I’m going to read the value of the TempData in the next view, which is rendered by the action method “Page1”.

<h2>Page1</h2> 
<p> 
    @{ 
        string 
strTempDataValueInPage1 = (string)TempData["MyTempDataValue"]; 
    } 
    
@strTempDataValueInPage1 
</p>
 

In order to test the above scenario, first you must render the view “Index” (since in that action method alone the tempdata value is initialized) and then you call the “Page1” view. As you can see that, TempData value is not available in the next request.

Wait! The conclusion is not yet over. I want to try some thing more. That is, as per the above codes:

1. First I render the “Index” page, where the Tempdata value is read and print it.
2. After I call the action method “Page1”.

What will happens if I didn’t read the value of Tempdata in “Index.cshtml” view and try to read the “Page1.cshtml” view. In order to test, I made the below changes in Index view.

Index.cshtml:
<h2>Index Page</h2> 
<p> 
    No Temp Data read here 
in Index.cshtml 
</p>


Page1.cshtml:

<h2>Page1</h2> 
<p> 
    @{ 
        string 
strTempDataValueInPage1 = (string)TempData["MyTempDataValue"]; 
    } 
    
@strTempDataValueInPage1 
</p>


Now, you got the value in the value of Tempdata in the next request. That means, your first request render the “Index” page, and the next request render the “Page1”.

If you refresh the above page, you will get the result as below: that is, the Tempdata is unavailable once it read. So you get the Tempdata value as empty.

So the conclusion is : After Tempdata value is initialized and it’s not yet read in the current request, then it will be available in the next request. Once it is read, it will not available.

Few words about Keep() and Peek() method:

After you read the tempdata, if you call the keep method, it will marks the all tempdata keys or specific key for retention.

If you want to fetch the key and mark the key for retention (keep the key for the next request) then you can go with Peek method.

Connection between Session and Tempdata:

Yes, Tempdata uses “Session” object in the backend. That is, whenever you use a tempdata it will handled by session. But the main difference is, the Tempdata will be removed (by default) after the first read.

At the same time, you may have the doubt, that either tempdata is specific to the user as like as “Session”? The answer is Yes. Since the Tempdata, is backed up with Session, Tempdata is also specific to user, like Session object.

Also, the another question is, since the Tempdata backed up with Session, what will happened if we go with same key for session and Tempdata as like below:

The answer is it won’t colloid. It will considered as a different one and it will serve its own purpose as per the convention.

In summary:
  1. TempData store the value using key.
  2. TempData backed up with Session.
  3. Need type casting when the stored value retrieved.
  4. The life time of tempdata is little bit tricky. It will be available till you read it first time. After you read it, it will be marked for deletion. So in the next request, it won’t available.  However, you can extend it’s life time by using keep and peek method.
Readers, did i missed anything? Share your feedback as comments.



Monday, October 10, 2016

ASP.Net : Binding Dropdown in ASP.Net

By Francis   Posted at   7:55 PM   Dropdown Control in Asp.Net No comments
Binding dropdown is a common need in ASP.Net. The below code snippet is used to bind the datatable values to the dropdown list.

Markup:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList runat="server" ID="ddlCity">
            </asp:DropDownList>
        </div>
    </form>
</body>
</html>

Code behind:

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                //Substitute your DB and Server name below
                string conString = @"Data Source=Your_DBServer_Name;Initial Catalog=Your_DB_Name;Integrated Security=True";
                DataTable dtCity = new DataTable("City");
                // Create Connection and get the DB values
                using (SqlConnection connection= new SqlConnection(conString))
                {
                    SqlCommand command = new SqlCommand(conString,connection);
                    command.CommandText = "Select city_code,city_description from tblCity";
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(dtCity);
                }
                // Set the Datasource
                ddlCity.DataSource = dtCity;
                ddlCity.DataValueField = "city_code";
                ddlCity.DataTextField = "city_description";
                // Finally Bind it
                ddlCity.DataBind();
            }
        }

Tuesday, August 2, 2016

ASP.Net MVC - ViewBag, ViewData and Tempdata

By Francis   Posted at   9:08 PM   ASP.Net MVC No comments



                  As an ASP.Net MVC developer, you may frequently involved with these terms like Tempdata, viewdata and viewbag. In this post, I’m going to discuss about what are they and what are the main difference between them.

ViewBag:

  1. ViewBag is dynamic in nature.
  2. There is no type casting needed.
  3. Life time lasts only for the current request.

View Data:
  1. ViewData is stored as a dictionary. You can store a value using a key.
  2. Type casting is needed, when you retrieve.
  3. Life time lasts only for the current request.

Tempdata:

  1. It’s also store the value using key.
  2. Need type casting when the stored value retrieved.
  3. The life time of tempdata is little bit tricky. It will be available till you read it first time. After you read it, it will be marked for deletion. So in the next request, it won’t available.  However, you can extend it’s life time by using keep and peek method.

Hope this helps!

Sunday, July 17, 2016

Visual Studio 2015 : Unable to open .CSHTML files

By Francis   Posted at   1:19 AM   Visual Studio Tips and Tricks 6 comments
                               
Unable to open CSHTML File in VisualStudio
                                 Visual studio 2015 is very cool IDE. It offers more and more benefits to increase the productivity of a developer. For my local development I’m using VS 2015 “Community” Edition. Also, I have updated with latest “Update 3” from here.

The Problem:
                         But after some days,  when i want to open a .cshtml file in my solution, VS throws some strange isssue, that is a pop up throws with the message “"Operation could not be completed. Invalid Pointer."

The Solution:
                     I’m not pretty much sure, this error is because of “Update 3”. But i soloved this issue by following the below steps:

  1. Close your VS instance
  2. Open the “Run” dialog (by pressing the short cut Windows Key +R).
  3. Type “%LocalAppData%” (without quotes).
  4. It will open the path “C:\Users\YOURUSERNAME\AppData\Local” in that navigate to “Microsoft –> Visual Studio –> 14.0 –>ComponentModelCache”.
  5. It contains some “cache” files, just delete them all.
  6. Now open the VS 2015 again. You can open the .cshtml files, without any problem.
The above trick, worked for me. This issue also discussed in this github thread. There are various solutions disscused over there, but i found this one is working for me, which is among one they discussed.

If you are one of the victim, hope this post may be useful for you!  Smile

Wednesday, July 13, 2016

WCF : Service Configuration Editor

By Francis   Posted at   3:44 PM   WCF No comments
WCF ConfigEditor                           

                  Windows Communication Foundation involves lot of configuration apart from service coding. Configuring the WCF service is a tedious process also. In order to configure the WCF Services, we need to put our hand mostly on the web.config file, where all the configuration elements resides. As a WCF service developer, I know it is little bit tedious process to configure an simple binding element in the configuration section.

In order to simplify (as much as possible) the configuration process, Microsoft provides an utility to configure the WCF service called “WCF Service Configuration Editor”, which is available as a built –in utility with Visual Studio.

In this particular post, i’m going to explain how to use the WCF Service Configuration editor and how to set different end points with it.

Open WCF Configuration Editor:
                             You can open the WCF Configuration Editor using the menu “Tools –> WCF Configuration Editor”. Otherwise, you can right click on the Web.config file and select “Edit WCF Configuration” on the context menu.

 Create Binding:

1. In the WCF Config Editor, select “Bindings” in the left “Configuration” tree view and click the “New Binding Configuration” link button.

Add Binding Configuration
2. It will open the “Create a new binding” dialog. In this select the respective binding you want. For this, example i will go with “Basic Http Binding” option and then click “OK”.


3. WCF Cofig Editor, will provide the all the attributes in the table format
under the “Binding” tab. You can configure the attribute by setting the valid values. I have set the “Name”  as “Sample Http Binding”.
Configure Binding Attribute

4. If you select “Security” tab, security related attributes are populated as a table format,where you can set the values related to security.

Security Settings

Create End Point:

1. Select the "Endpoints” node in the “Configuration” treeview. Then click “New Client Endpoint” link button.


2. Previously we have created “Basic Http Binding”, So we need to select the “binding” as “Basic Http Binding”.
                                      

3. For “Contract” attribute value, click the browse button and select the WCF service’s dll location. It will extract the Contract from the dll and put it there. Otherwise, you can manually set it.
4. Set the “Address” attribute as the web service location, that is the url, where the WCF service was hosted.
I have set the mandatory attribute alone in the above steps. There are lot of options will be available under the “Identity” tab. if you need any one of these you can set it.

So we are good with our configuration, just save it using “File –> Save”. As a result, the “Web.config” file will be updated with the values which we have configured just now.


Web.config with configured binding and endpoint
As a whole, if you are going to configure some complex binding at this time “WCF Configuration Editor” really helpful!

Readers! I hope this article is helpful. Please let me know your thoughts as comments!
Connect with Us