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

MVC Interview Questions and Answers

Model View Controller


By reading these MVC interview question it does not mean you will go and clear MVC interviews. The whole purpose of this Post is to quickly brush up your MVC knowledge before you for the MVC interviews.
Before Going for Question Answers, i will give you a little bit of introduction about MVC.

What is MVC?

MVC is a framework pattern that splits an application’s implementation logic into three component roles: models, views, and controllers.
  • Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
  • View: The user interface that renders the Model into a form of interaction.
  • Controller: Handles a request from a View and updates the Model that results in a change of the Model’s state.To implement MVC in .NET, we need mainly three classes (ViewController and the Model).

    Explain MVC Architecture?

  •              The architecture is self explanatory. The browser (as usual) sends a request to IIS, IIS searches for the route defined in MVC application and passes the request to the controller as per route, the controller communicates with the model and passes the populated model (entity) to View (front end), Views are populated with model properties, and are rendered on the browser, passing the response to browser through IIS via controllers which invoked the particular View.

  Features of MVC 2.0

  • Introduction of UI helpers with automatic scaffolding with customizable templates
  • Attribute-based model validation on both client and server
  • Strongly typed HTML helpers
  • Improved Visual Studio tooling
  • There were also lots of API enhancements and “pro” features, based on feedback from developers building a variety of applications on ASP.NET MVC 1.0, such as:
    • Support for partitioning large applications into areas
    • Asynchronous controllers support
    • Support for rendering subsections of a page/site using Html.RenderAction
    • Lots of new helper functions, utilities, and API enhancements

  Features of MVC 3.0

  • The Razor view engine
  • Support for .NET 4 Data Annotations
  • Improved model validation
  • Greater control and flexibility with support for dependency resolution and global action filters
  • Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
  • Use of NuGet to deliver software and manage dependencies throughout the platform

  Features of MVC 4.0

  • ASP.NET Web API
  • Enhancements to default project templates
  • Mobile project template using jQuery Mobile
  • Display Modes
  • Task support for Asynchronous Controllers
  • Bundling and minification

  Advantages of MVC

  1. Provides a clean separation of concerns between UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller)
  2. Easy to UNIT Test
  3. Improved reusability of views/model. One can have multiple views which can point to the same model and vice versa
  4. Improved structuring of the code

  Explain Routing in MVC

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
Routing within the ASP.NET MVC framework serves two main purposes:
  • It matches incoming requests that would not otherwise match a file on the file system and maps the requests to a controller action.
  • It constructs outgoing URLs that correspond to controller actions.

  Now Ready for Question – Answers:

1. What are the 3 main components of an ASP.NET MVC application?
1. M – Model
2. V – View
3. C – Controller
2. In which assembly is the MVC framework defined?
System.Web.Mvc
3. Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.
4. What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.
View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.
Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.
5. What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.
6. Which approach provides better support for test driven development – ASP.NET MVC or ASP.NET Webforms?
ASP.NET MVC
7. What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.
8. Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don’t have to run the controllers in an ASP.NET process for unit testing.
9.Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.
10. What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.
11.Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax
12. Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult
13.What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.
14. What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.
15. What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment – Controller Name
2nd Segment – Action Method Name
3rd Segment – Parameter that is passed to the action method
Example: http://dotnetternikhil.com/Nikhil/Home/1
Controller Name = Nikhil
Action Method Name = Home
Parameter Id = 1
16. ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.
17.What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.
An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user’s action and therefore are more easily understood by users.
18. What are the 3 things that are needed to specify a route?
1. URL Pattern – You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler – The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route – Name is optional.
19. Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.
20. What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
21. What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.
22. How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}
23. What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface
24. Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern – This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern – Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.
25. What are the 2 popular asp.net mvc view engines?
1. Razor
2. .aspx
26. What symbol would you use to denote, the start of a code block in razor views?
@
27. What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

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 !!