MVC Interview Question - 4

What is HTML Helpers in MVC

The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view.


Below render CheckBox in MVC Application

<%= Html.CheckBox("bookType") %>

TextBox Helper

Enter your name: <%= Html.TextBox("name") %>

List out the HTML Helpers Available in MVC


ActionLink — Links to an action method.

BeginForm * — Marks the start of a form and links to the action method that renders the form.
CheckBox * — Renders a check box.
DropDownList * — Renders a drop-down list.
Hidden — Embeds information in the form that is not rendered for the user to see.
ListBox — Renders a list box.
Password — Renders a text box for entering a password.
RadioButton * — Renders a radio button.
TextArea — Renders a text area (multi-line text box).
TextBox * — Renders a text box

What is the AJAX Helpers in ASP.Net


AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc namespace.


Following example shows how to use AJAX action link using action and controller in Asp.Net MVC.


@Ajax.ActionLink("Fatch Data", "GetData", new AjaxOptions {UpdateTargetId = "Data-container", HttpMethod = "GET" })


Here is the html output of above code block.


<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Data-container" href="/Home/GetData"> Fatch Data </a>




What is JSON Binding in MVC?

JavaScript Object Notation (JSON) binding support started from ASP.Net MVC3 onwards via the new JsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server.


What is Dependency Resolution in MVC?

Dependency Resolver again has been introduced in ASP.Net MVC3 and it is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.


Explain Bundle.Config in ASP.Net MVC4?

"BundleConfig.cs" in ASP.Net MVC4 is used to register the bundles by the bundling and minification system. Many bundles are added by default including jQuery libraries like - jquery.validate, Modernizr, and default CSS references.

What is the difference between View and Partial View



View Partial View
It contains the layout page It does not contain the layout page
Before any view is rendered, viewstart page is rendered Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml.page
View might have markup tags like body, html, head, title, meta etc. Partial view is designed specially to render within the view and just because of that it does not consist any mark up
View is not lightweight as compare to Partial View We can pass a regular view to the RenderPartial method


How to perform validation in MVC ?

one of the way to do validation in MVC using data annotations.
it is attributes whih can be applied to model peoperties.

See the below example.





public class Customer

{

    [Required(ErrorMessage="Customer code is required")]

    public string CustomerCode

    {

        set;

        get;

    } 

}  



In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.




<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))

{ %>

<%=Html.TextBoxFor(m => m.CustomerCode)%>

<%=Html.ValidationMessageFor(m => m.CustomerCode)%>

<input type="submit" value="Submit customer data" />

<%}%> 




How can we enable data annotation validation on client side?

It’s a two-step process: 
first reference the necessary jQuery files.



<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>



The second step is to call the EnableClientValidation method.








<% Html.EnableClientValidation(); %> 



How to use Jquery Plugins in ASP.Net MVC validation?

We can use dataannotations for validation in ASP.Net MVC. If we want to use validation during runtime using Jquery then we can use Jquery plugins for validation. Eg: If validation is to be done on customer name textbox then we can do as :




$('#CustomerName').rules("add", {

required: true,

minlength: 2,

messages: {

required: "Please enter name",

minlength: "Minimum length is 2"

}



});






MVC Interview Question                          MVC Interview Question - 1




Posted in Labels: , | 0 comments

MVC Interview Question

Posted in Labels: , | 0 comments

MVC Interview Question - 3

What is ViewData and View Bag?
ViewData, ViewBag is use for passing data from controller to
view and in next request. 

Viewdata contains the key, value pairs as dictionary and this is derived from class : "ViewDataDictionary". In action method we are setting the value for viewdata and in view the value will be fetched by typecasting.

ViewData and ViewBag are almost similar.

Similarity between ViewData and View Bag
1. Helps to maintain data when you move from controller to view.
2. Used to pass data from controller to corresponding view.

3. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and is accessible using strings as keys.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
ViewData requires typecasting for complex data type and check for null values to avoid error.
ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:






public ActionResult Index()

{

    ViewBag.Name = "Monjurul Habib";

    return View();

}





public ActionResult Index()

{

    ViewData["Name"] = "Monjurul Habib";

    return View();





In View:



@ViewBag.Name 

@ViewData["Name"] 





What is the TempData

TempData is use for Passing data from Controller to View in ASP.NET MVC.
TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary.

TempData stays for a subsequent HTTP Request as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempdData can be used to maintain data between controller actions as well as redirects.

Below is sample example of TempData.





 //Controller Action 1 (TemporaryEmployee)

 public ActionResult TemporaryEmployee()

{

                Employee employee = new Employee

                {

                        EmpID = "121",

                        EmpFirstName = "Imran",

                        EmpLastName = "Ghani"

                };

                TempData["Employee"] = employee;

                return RedirectToAction("PermanentEmployee");

}



 //Controller Action 2(PermanentEmployee)

 public ActionResult PermanentEmployee()

{

               Employee employee = TempData["Employee"] as Employee;

               return View(employee);

 }





As in above example, we store an employee object in TempData in Controller Action 1 (i.e. TemporaryEmployee) and retrieve it in another Controller Action 2 (i.e. PermanentEmployee). But If we try to do the same using ViewBag or ViewData, we will get null in Controller Action 2 because only TempData object maintains data between controller actions. An important thing about TempData is that it stores contents in Session object


What is the REST ?

Rest is Representational State Transfer.
REST is an architectural style which uses HTTP protocol 
methods like GET, POST, PUT, and DELETE to access the data.
ASP.Net MVC works in this style. 
In ASP.Net MVC 4 there is a support for Web API which uses 

to build the service using HTTP verbs.


MVC Interview Question                                  MVC Interview Question - 4

Posted in Labels: , | 0 comments

MVC Interview Question - 1

What is the MVC ?

MVC is a software architecture pattern for developing web application. 

It is handled by three objects Model-View-Controller.

Model– It represents the application data domain. In other words applications business logic is contained within the model and is responsible for maintaining data


View– It represents the user interface, with which the end users communicates. In short all the user interface logic is contained within the VIEW



Controller– It is the controller that answers to user actions. Based on the user actions, the respective controller responds within the model and choose a view to render that display the user interface.  The user input logic is contained with-in the controller



Explain the Page LifeCycle of ASP.Net MVC

Below are the processed followed in the sequence.

App initializWhat is Separation of Concerns in ASP.NET ASP.Net MVCation
Routing
Instantiate and execute controller
Locate and invoke controller action
Instantiate and render view.



The main advantages of ASP.net MVC are



1.It provides RAD development

2.Enables the full control over the rendered HTML.

3.Easy integration with JavaScript frameworks.
4.Following the design of stateless nature of the web.
5.No ViewState and PostBack events
6.Support Full SEO using URL rewriting.
7.Easy development model for developers those coming from winform development
8.Provides clean separation of concerns(SoC).

What is the main assembly for MVC framework.
System.Web.Mvc

List out few different return types of a controller action method?

ViewResult - Renders a specified view to the response stream

EmptyResult - An empty response is returned

PartialViewResult - Renders a specified partial view to the response stream

FileContentResult - Returns a file to the client

RedirectResult - Performs an HTTP redirection to a specified URL

RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

JsonResult - Serializes a given object to JSON format

JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

ContentResult - Writes content to the response stream without requiring a view

FileStreamResult - Returns a file to the client, which is provided by a Stream

FilePathResult - Returns a file to the client


Is MVC suitable for both Windows and Web applications?

The MVC is most suitable to web application.
For Windows application WPF,MVP,MVVM is more suitable.



What is the latest version of MVC?

MVC 6 is the latest version which is also termed as ASP VNEXT.

Difference between MVC 2, MVC 3 ,MVC 4,MVC 5 and MVC 6?

MVC 2

Client-Side Validation

Templated Helpers

Areas

Asynchronous Controllers

Html.ValidationSummary Helper Method

DefaultValueAttribute in Action-Method Parameters

Binding Binary Data with Model Binders

DataAnnotations Attributes

Model-Validator Providers

New RequireHttpsAttribute Action Filter

Templated Helpers

Display Model-Level Errors


MVC 3

Razor

Readymade project templates

HTML 5 enabled templates

Support for Multiple View Engines

JavaScript and Ajax

Model Validation Improvements


MVC 4

ASP.NET Web API

Refreshed and modernized default project templates

New mobile project template

Many new features to support mobile apps

Enhanced support for asynchronous methods


MVC 5

One ASP.NET

Attribute based routing

Asp.Net Identity

Bootstrap in the MVC template

Authentication Filters

Filter overrides

MVC 6

ASP.NET MVC and Web API has been merged in to one.

Dependency injection is inbuilt and part of MVC.

Side by side - deploy the runtime and framework with your application

Everything packaged with NuGet, Including the .NET runtime itself.

New JSON based project structure.

No need to recompile for every change. Just hit save and refresh the browser.

Compilation done with the new Roslyn real-time compiler.

vNext is Open Source via the .NET Foundation and is taking public contributions.

vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.




MVC Interview Question                                     MVC Interview Question - 2

Posted in Labels: , | 0 comments

MVC Interview Question - 2

How can I return string result from Action in ASP.Net MVC?

Below is the code snippet to return string from action method :




public ActionResult TestAction() {

return Content("Hello Test !!");

}



How to return the JSON from action method in ASP.Net MVC?

Below is the code snippet to return string from action method :



public ActionResult TestAction() {

return JSON(new { prop1 = "Test1", prop2 = "Test2" });



}



What is the Razor in ASP.Net

Razor is not a new programming language itself, but uses C# syntax for embedding code in a page without 

the ASP.NET delimiters: <%= %> . 

It is a simple-syntax view engine and was released as part of ASP.NET MVC 3. 


The Razor file extension is "cshtml" for the C# language


Read below article for more about Razor.


http://www.codeproject.com/Articles/639695/Getting-Started-with-Razor-View-Engine-in-MVC


Explain what is routing? What are the three segments for routing is important?


Routing helps you to decide a URL structure and map the URL with the Controller.


The three segments that are important for routing is


ControllerName

ActionMethodName
Parameter

Explain how routing is done in MVC pattern?

There is a group of routes called the RouteCollection, which consists of registered routes in the application.  The RegisterRoutes method records the routes in this collection.  A route defines a URL pattern and a handler to use if the request matches the pattern. The first parameter to the MapRoute method is the name of the route. The second parameter will be the pattern to which the URL matches.  The third parameter might be the default values for the placeholders if they are not determined.


Where is the route mapping code written in MVC?

The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.

For more details 

http://dotnet-magic.blogspot.in/2016/03/important-of-routeconfigcs-in-mvc.html

Can we map multiple URL’s to the same action?

Yes, you can, you just need to make two entries with different key names and specify the same controller and action.

What is the attribute based routing in MVC 


This new feature introduce in MVC 5.

By using the "Route" attribute we can define the URL structure. 
For example in the below code we have decorated the "GoAboutus" action with the route attribute. 
The route attribute says that the "GoAboutus" can be invoked using the URL structure "Users/about".




public class HomeController : Controller

{

       [Route("Users/about")]

       public ActionResult GoAboutus()

       {

           return View();

       }

}


How to enable Attribute Routing?

Just add @Model.CustomerName the method : "MapASP.Net MVCAttributeRoutes()" to enable attribute routing as shown below:



public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //enabling attribute routing
        routes.MapASP.Net MVCAttributeRoutes();
        //convention-based routing
        routes.MapRoute
        (
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Customer", action = "GetCustomerList", id = UrlParameter.Optional }
        );
    }


Mention what are the two ways to add constraints to a route?


The two methods to add constraints to a route is

Use regular expressions
Use an object that implements IRouteConstraint Interface

Below is example of Regular expression



routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
 );


The regular expression \d+ matches one or more integers. This constraint causes the Product route to match the following URLs:


/Product/3

/Product/8999
But not the following URLs:

/Product/apple

/Product


What is the use of the default route {resource}.axd/{*pathinfo} ?

This default route prevents request for a web resource file such as Webresource.axd or ScriptResource.axd from being passed to the controller.



What are child actions in ASP.Net MVC?

To create reusable widgets child actions are used and this will be embedded into the parent views. In ASP.Net MVC Partial views are used to have reusability in the application. Child action mainly returns the partial views


What is the ChildActionOnly attribute ?

The ChildActionOnly attribute ensures that an action method can be called only as a child method from within a view. An action method doesn’t need to have this attribute to be used as a child action, but we tend to use this attribute to prevent the action methods from being invoked as a result of a user request. Having defined an action method, we need to create what will be rendered when the action is invoked. Child actions are typically associated with partial views, although this is not compulsory.

1. [ChildActionOnly] allowing restricted access via code in View
2. State Information implementation for specific page URL. Example: Payment Page URL (paying only once) razor syntax allows to call specific actions conditional





[ChildActionOnly]

public ActionResult MenuBar()

{

//Logic here

return PartialView();



}




MVC Interview Question                           MVC Interview Question - 3


Posted in Labels: , | 0 comments