Skip to main content

Posts

Showing posts from July, 2014

Difference between ViewData, ViewBag and TempData in MVC

While working with ASP.NET MVC applications one need to retain data or need to transfer data from controller to the view or one controller to another controller. In ASP.NET MVC, there are three types of objects - ViewBag, ViewData and TempData, use to pass data from controller to view and controller to controller. Each object has its own functionality, importance and area in which it uses and one needs to decide when to use ViewData, ViewBag or TempData. In this post we’ll look on key points of these three objects. ViewData: ViewData helps to maintain data when you move from controller to view. Example: //In Controller defines ViewData FullName. public ActionResult Index() {     ViewData[ "FullName" ] = "Sandeep Kumar" ;     return View(); } //In View use ViewData @ ViewData[ "FullName" ] Mentioned below are some key points about ViewData: ·          ViewData is used to pass data from controller to view.

Use TempData Keep or Peek method to persist data in MVC

TempData used to transfer data between controllers or between actions. There is one point to note that TempData is only work during the current and subsequent request and it is generally used to store one time message. But one can persist data in TempData object even after request completion with the help of Keep() or Peek() method. TempData.Keep(): TempData.Keep() method keep value in TemData object at the end of current request. There are two overloaded keep methods available with TempData: ·          void Keep(): This method make ensures that all the items in TempData are not destroyed on current request completion. ·          void Keep(string key): One can persist the specific item in TempData by passing in the item name. TempData.Peek(string key): It returns an object that contains the element that is associated with the specified key, without marking the key for deletion. Example: //Set some value to TempData TempData[ "value" ] = "

How to encode or decode HTML in jQuery

In this post, I’ll show you how you can encode or decode (if you ever need to do so) supplied HTML using jQuery. This is quite easy just create two separate method for encoding and decoding as given below.   function encodeHTML (text) {     if (text) {         return jQuery( '<div />' ).text(text).html();     } else {         return '' ;     } } function decodeHTML (text) {     if (text) {         return $( '<div />' ).html(text).text();     } else {         return '' ;     } } Test the both method to encode or decode HTML.   $( function () {     //pass the html to encode.      alert(encodeHTML( 'You & me are good friends' ));     //pass the html to decode.      alert(decodeHTML( 'You &amp; me are good friends' )); }); Check working sample and code