Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, February 25, 2015

What is ViewBag, ViewData and TempData in MVC ?


In ASP.NET MVC, Generally we have three options for passing data from Controller to View and in the request. 

And that three options are :
1. ViewBag
2. ViewData and
3. TempData

ViewBag and ViewData are basically same and TempData have some additional responsibilities to perform.


ViewBag and ViewData
ViewBag and ViewData are generally used for same purpose. Both are used to transfer the data from controller to view and both of having a short life which lies only in current request. Short life means the value becomes null during the next request or any redirection occurs.

ViewBag is a dynamic property which is able to set and get value dynamically.
ViewBag is basically a wrapper around the ViewData.

ViewData is dictionary of an object which is accessible by string as a "key".
ViewData is a property of Controller that exposes an instance of ViewDataDictionary.


Difference between ViewBag and ViewData

ViewBag ViewData
ViewBag is a dynamic property
ViewData is a dictionary of object which if accessible using string as a "key".
ViewBag is a new dynamic feature of C# 4.0
ViewData is derived from ViewDataDictionary class.
Works with .Net framework 4.0
Works with .Net framework 3.5
It doesn't require typecasting for complex data type.
It requires typecasting for complex data type.


Example of ViewBag

At Controller

Public ActionResult Index()
{
    ViewBag.Author = "Nikhil";
    Return View();
}

At View
<label>@ViewBag.Author</label>
Example of ViewData

At Controller
Public ActionResult Index()
{
    ViewData["Author"]= "Nikhil";
    Return View();
}
At View

<label>@ViewData["Author"] </label>


TempData

TempData is also a dictionary which is derived from TempDataDictionary class.
TempData is stored data just like a session for limited period of time.
TempData holds the data for the time of HTTPRequest means it holds the data between two consecutive request.
So, the TempData is useful for transferring the data from one Controller to another Controller and one Action to another Actions.
Initially the TempData uses the session variables. It helps to maintain the data between controllers and actions. It requires the typecasting for such complex data types.
TempData is generally used to save one time message. but you can keep the value after the completion of request by using  keep()  method.

Example of TempData

Public ActionResult Index()
{
   var dbModelData = new Author (){ Name = "Nikhil", UserName = "DotNetter"};
   TempData["objModel"] = dbModelData;
   Return RedirectToAction("Login");
}
Public ActionResult Index()
{ 
   var modelDetails = TempData["objModel"];
   Return View(modelDetails);
}
At the End :

In ASP.NET MVC, we have three options ViewBag, ViewData and TempData for sending the data between Controllers and Views and in next request. Basically ViewBag and ViewData are same and used for sending data from Controller to View and TempData is used during current and subsequent request that means you can pass data between Controllers and Actions with the help of TempData.

Tuesday, December 23, 2014

Check whether an email address is valid or not ?

Some times, we require some common function like Get Random GUID, or some validations like passowrd is strong or not.

So, here i show you the validation of Email address field that checks whether the entered email address is valid or not ?


I have created a function "CheckEmail", which accepts the EmailAddress imput as an parameter.
You have to pass your input Emailaddress value to this function and this function will return you a boolean (true/false), if the entered email address is valid then it will return true until false.

    //<param name="emailAddress">Your Email Address</param>
    public static bool CheckEmail(string emailAddress)
    {
        bool isValid = true;
        if (string.IsNullOrWhiteSpace(emailAddress.Trim()))
        {
            isValid = false;
        }
        else
        {
            RegexStringValidator re = new RegexStringValidator(@"^[a-zA-Z0-9][-\w\.]*@([a-zA-Z0-9][\w\-]*\.)+[a-zA-Z]{2,3}$");
            try
            {
                re.Validate(emailAddress);
            }
            catch
            {
                isValid = false;
            }
        }
        return isValid;
    }
   
    For RegexStringValidator class, you have to add this namespace
using System.Configuration

Monday, December 22, 2014

Difference between ApiController and Controller in ASP.NET MVC

In Today's generation all the peoples are very smart. They are using mobiles, tablets etc. device in those days rather than browser and these device have unlimited apps for make a life smooth. At the end, we all are moving from the web world towards the app world.


So, why not we will develop a worth program which will be helpful in both web and app world.
So, For that i suggest go through ApiControllers.

Difference :

1) You can use controller to render your normal views only.
but using the ApiController action only returns the data which is serialized and sent to client.
So, that you can use it any Html based application.

2) You can self hosting using ApiController but not from MVC Controllers.

3) If you are aware with ASP.NET MVC then you are already knows about the controllers.
And the APIControllers are same as MVC controllers, but it inherits the ApiController class instead of the Controller class.

4)  APIControllers is a lightweight architecture excepting the web Apps.

5)  MVC Controller shows the URL Samples matching the default route pattern"{controller}/{action}/{id}". and the ApiController shows "api/{controller}/{id}".

6) Web API Supports the self hosting, content negotiation where the MVC doesn't support it.

7) Use Controller when - If you're writing an HTML based web/internet application (with the occasional AJAX call returning json here and there).
Use ApiControllers When - If you want to provide a data driven/REST-ful interface to a system.

8) For Example,
     //In ASP.NET MVC
     public class PostsController : Controller
     {
         // GET: /Tweets/
         [HttpGet]
         public ActionResult Index() {
               return Json(Facebook.GetAllPosts(), JsonRequestBehavior.AllowGet);
         }
     }

     //ASP.NET Web API
public class TweetsController : ApiController { // GET: /Api/Tweets/ public List<Posts> GetAllPosts() { return Facebook.GetAllPosts(); } }
So, You have to use the API which is compatible with the browsers and all the modern devices apps.
Actually, the Web API is a open source platform for building a REST-ful services over the .Net Framework.  



Now, I hope you have got when to use Web API over MVC and how it works.
Please keep commenting every author needs motivation.

Friday, December 19, 2014

Facebook Integration in MVC 3.0 (.Net)


Now, Time for Facebook Integration in .Net MVC 3.0.
Step 1 :  Download Library package reference of Facebook from NuGet Package Installer.
Step 2 :  import namespace of facebook as like,             
    using facebook;
Step 3 :  This uri method handles Our call back method that will returns from facebook site after Completed Login screen. 
private System.Uri RedirectUri
{
      get
      {
            var uribuilder = new UriBuilder(Request.Url);
            uribuilder.Query = null;
            uribuilder.Fragment = null;
            uribuilder.Path = Url.Action(“FacebookCallBack”);
            return uribuilder.Uri;
      }
}
public ActionResult Facebook()
{
      var fb = new FacebookClient();
      var loginurl = fb.GetLoginUrl(new
            {
                  client_id = “463931757029793”,
                  client_secret = “add31b78281d6ffccc7d1b887f77d9d4″,
                  redirect_uri = RedirectUri.AbsoluteUri,
                  responce_type = “code”,
                  scope = “email,publish_stream,user_hometown,user_website”
            });
      return Redirect(loginurl.AbsoluteUri);
}
Step 4 :  Now, get the Details from facebook Client..
public ActionResult FacebookCallBack(string code)
{
      var fb = new FacebookClient();
      dynamic result = fb.Post(“oauth/access_token”, new
            {
                  client_id = “463931757029793”,
                  client_secret = “add31b78281d6ffccc7d1b887f77d9d4″,
                  redirect_uri = RedirectUri.AbsoluteUri,
                  code = code
            });
      var accessTocken = result[0];
      Session[“AccessTocken”] = accessTocken;
      fb.AccessToken = accessTocken;
      dynamic me = fb.Get(“me?fields=first_name,last_name,id,email”);
      String email = me[3];
      return RedirectToAction(“LoginView”);
}
Now, Finally this is Done…!!!
Yippee. Always Enjoy coding !!