ASP.Net MVC interview questions and answers

1) Explain about MVC page life cycle?

Requset first hit Global.asax file after its goto RouteConfig.RegisterRoutes(RouteTable.Routes); method RouteConfig.cs . here it finds appropriate controller and action method

2)Types of routings available in MVC?

There are two types of routings available in ASP.NET MVC.

1)Conventional Routing 
2) Attribute based routing

Conventional Routing : 

-It is globally configured routing , available at application level , defined in RouteConfig file in MVC  --Defined in Startup.cs file in ASP.NET Core MVC.
-Its well suited for MVC apps

Attribute based routing: 

-This routing available at an  action method level, When request is reached to the action method its redirect to another route.
-Its well suited for API apps

3)What is Route parameters in MVC?

-Route parameters are variable values extracted from URL ,  Sometimes it may be optional or having default values .
-if you want you can apply constraints  to this route parameters.

4)How to apply constraints on route values in MVC?

-While passing parameters to an action methods these constraints are very useful.
In MVC we have different types of constraints , some of the ore listed below.

{price : decimal} ->accepts all decimal values
{price : min(18)}-> price should be minimum 18 or greater 
{price : int?}->? is an optional parameter so that price should be an integer or null
{productName: length(6)} -> Matches product name with six characters 

Ex:
{controller}/{action method}/{id:length(4)}

5) What is the use of IActionConstraint  in MVC?

It helps to compiler to chose appropriate method name , if more than one action method matching with URL.
Using IActionConstraint's such as HttpGet , HttpPost etc ..We achieve the same 
 
6)Model Binding in MVC applications?

-Model Binding allows us to map and bind the HTTP request data with a model
-Model binding seems simple but it’s actually a relatively complex framework composed of a number of parts that work together to create and populate the objects that your controller actions require.
-The DefaultBinder object handles the default Model Binding.
-If you want you can customize ModelBinding. 
 -MVC provides the System.Web.Mvc.DefaultModelBinder that is used to work with the simple types or classes and collections. 

7) What are the model binding sources?

Formvalues 
Route values
Query string values

Binder always checking the values in above mentioned order. If one property value found in Form values , not checking the same property  value in remaining two.

If no values found from above sources , it's return null or unexpected value. 

8) What is Form values in ASP.NET MVC?

Form values always sent from request body of the HTTP request using post operation.

9)Is modelbinder case sensitive ?

No 

10)What type of data stored in modelbinding sources?

-Only string data , While associating with action method parameters conversation is happening .
-Binder is responsible for conversation 

12)If your passing list object to the view. how can we implement list object in a view?

At that time we use IEnumerable interface on top of the view


@model IEnumerable<MVCDemo.Models.Employee>


13)How can we pass ID from view to controller using action link?


@Html.ActionLink(employee.Name, "Details", new { id = employee.EmployeeId })


From above syntax when user click on Employee name, employee id is passed to the "Details" action method.


14)What is strongly typed views?


-The view which bind with any model is called as strongly typed view. 
-You can bind any class as model to view.You can access model properties in view. 
-You can use data associated with model to render controls. 

15)How to bind data to the dropdown in RazorSyntax?


@Html.DropDownList("Products", new List<SelectListItem>

{
new SelectListItem { Text = "Pen", Value="Pen" },
new SelectListItem { Text = "Paper", Value="Paper" }
}, "Select Produts")

16)What is FormCollection?


-FormCollection is class which is automatically receives the values from the view to controller action method.

its contain the values in the form of key/value pairs.
ex:
[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
Product productinfo= new Product();
    // Retrieve form data using form collection
productinfo.Id =formCollection["Id"];    
productinfo.Name = formCollection["Name"];
}

17)How is model binding works in MVC?


Form controls names  and parameter names of the action method should be same.


Mapping is done by modlebinder.


18)What is ModelState.IsValid ? (or) What is 'IsValid' property? 


-'IsValid' is a boolean property.Its return either true or false.


-If there is no model validation error its return True.


-If there is any model validation error its return false.



19)What is 'ActionName' name attribute in MVC (or) How to use different name for action method in requested URL in MVC?


If you want to hide the actual action method name then you should use this. 


Example



[ActionName("Products")]

public ActionResult GetProducts()
{
    return View();
}

now it shows "Products" in URL instaed of GetProducts.


20)What is Updatemodel() method in MVC?


It is using for updating view values with model automatically.

ex:
[ActionName("Products")]
public ActionResult GetProducts()
{

Product productinfo = new Product();
productinfo.Price="200";
Updatemodel(productinfo)
return View();

}


From above code Product class values automatically updated with view values. 


21)Edit option action method code with Entity framework?


[HttpGet]

public ActionResult Edit(int id)
{
    ProductsBusinessLayer productBusinessLayer = 
           new ProductsBusinessLayer();
    Product product = 
           productBusinessLayer.Products.Single(prd => prd.ID == id);
            
    return View(product);
}

22)How to create a readonly textbox in ASP.NET MVC3, With Razor view engine ? 


@Html.TextBoxFor(m => m.ProductID, new { @readonly="readonly" })


return RedirectToAction("Index");


How to disable the feild against editing but shows value of it in MVC,With Razor view engine ?


Use DisplayFor instead of  EditorFor
Using @Html.DisplayFor(model => model.Text) instaed of @Html.EditorFor(model => model.Text).


23)What is the difference between Razor view Engine and aspx view engine?


Razor views having extension of cshtml

Aspx views having extension of aspx.
in aspx views: To switch between HTML code and Server code here we use <%: 
in Razor views: To switch between HTML code and Server code here we use @

24)What is App_Data folder in ASP.Net?


App_Data folder contains .mdf file XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information.


25)Membership Configuration in ASP.NET Application?


You can enable ASP.NET Membership by editing the Web.config file in application or 


ASP.NET Membership is configured using the membership element in the Web.config file for your application (OR) Web Site Administration Tool, which provides a wizard-based interface. As part of membership configuration, you specify:
The membership element is a sub-element of the system.web section.

<system.web>

<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
    
</membership>
</system.web>

Using memeber ship you can specify:


1)Which membership provider (or providers) to use

2)Password options 
3)Users and passwords. If you are using the Web Site Administration Tool, you can create and manage users directly. Otherwise, you must call membership functions to create and manage users programmatically.

<system.web>

    <authentication mode="Forms" >
      <forms loginUrl="login.aspx"
        name=".ASPXFORMSAUTH" />
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear />
        <add 
          name="SqlProvider" 
          type="System.Web.Security.SqlMembershipProvider" 
          connectionStringName="MySqlConnection"
          applicationName="MyApplication"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="true"
          requiresUniqueEmail="true"
          passwordFormat="Hashed" />
      </providers>
    </membership>
  </system.web>



26)HTML DropDown helper in MVC and  their syntax ?


binding data to dropdown list


Controller Code:


public ActionResult Index()

{
    // Connect to dataaccess layer

    SampleDBContext db = new SampleDBContext();


    // Retrieve Products

    ViewBag.Products = new SelectList(db.Products, "Id", "Name");
            
    return View();
}

View code:


@Html.DropDownList("Products", "Select Product")



27)How to apply CSS to HTML helpers? 


With in the control


@Html.TextBox("name", "John", new { style = "background-color:blue; color:White; font-weight:bold", title="Please enter your first name" })


With help of the css class


define css class


.TestCss

{
background-color:blue; 
color:White; 
font-weight:bold
}

@Html.TextBox("name", "John", new { @class = "TestCss" })



28)What is Jsonrequestbehavior.AllowGet? (or) how can i return JSON result from HTTP GET request?

Which explicitly informs that the Asp.Net MVC framework that its acceptable to return JSON data in response to an HTTP GET request.

by default ASP.NET MVC not return JSON data in response to an HTTP GET request in order to avoid security reasons called JSON hijaking.


public ActionResult JsonAuction(long id)

{
var db= new DataContext();
var response = db.Auctions.Find(id);
return Json(response, JsonRequestBehavior.AllowGet);
}


29)How can i request JSON data from my controller? (or)  $.ajax() method syntax?



 $(function () {

        $("button").click(function () {
            $.ajax({
                type: "POST",
                url: "/Receiver/JsonAuction/",
                data: car,
                datatype: "html",
                success: function (data) {
                    $('#result').html(data);
                }
            });
        });
    });

30)What is display attribute in MVC?


Using to specify localizable strings for types and members of entity partial classes.


[DisplayName("Product ID")]

public string ProductID { get; set; }

or


[Display(Name="Product ID")]

public string ProductID { get; set; }

Now its shows ProductID like Product ID.


31)Use of  @Html.DisplayForModel() ?


Returns HTML markup for each property in the model


32)Scaffoldcolumn attribute in MVC?


If you dont want to expose particular column data then use [ScaffoldColumn(false)]


but its only working with .DisplayForModel().


 [ScaffoldColumn(false)]

    public object ProductID;

33)What is MetadataTypeAttribute in MVC? 

Specifies the metadata class to associate with a data model class

How to apply DataAnnotations with Entity Data Model (EDM), LINQ to SQL, and other data models in MVC?

you are using the Microsoft Entity Framework to generate your data model classes then you cannot apply the validator attributes directly to your classes. Because the Entity Framework Designer generates the model classes, any changes you make to the model classes will be overwritten the next time you make any changes in the Designer.

If you want to use the validators with the classes generated by the Entity Framework then you need to create meta data classes. You apply the validators to the meta data class instead of applying the validators to the actual class.

[MetadataType(typeof(ProductMetadata))]
public partial class Product
{

}

public class ProductMetadata
{
   
}

34)What is the use of DataTypeAttribute in MVC?

To provide additional type information for a data field that is more specific than the database intrinsic type. 


"DataTypeAttribute"  use the  DataType enumeration for specifing specific type.


[DataType(DataType.EmailAddress)]



public class ProductMetadata

{
    [DataType(DataType.EmailAddress)]
    public string CareAddress { get; set; }

    [DataType(DataType.Currency)]

    public int Price { get; set; }
}


35)What is uihint attribute in asp.net mvc?


Specifies the template or user control that Dynamic Data uses to display a data field.If you create a custom user control, you use the UIHint property on a property so that the property is rendered using the custom user control


[MetadataType(typeof(ProductMetadata))]

public partial class Product
{

}

public partial class ProductMetadata
{
    [UIHint("UnitsInStock")]
    [Range(100, 10000, 
    ErrorMessage = "Units in stock should be between {1} and {2}.")]
    public object UnitsInStock;

}

36)What is RenderBody() mwethod in MVC?

It acts like a a placeholder.here view-specific pages you create show up, "wrapped" in the layout page

37)What is POCO classes?

Code first approach allows you create model by using simple classes is known as  POCO classes

POCO (Plain old CLR objects)

38)What is the use of DbContext class?

Its responsible for retrieving , inserting , updating class instances in Database

Ex:

Public class Student 
{

}

Public class StudentDBContext : DbContext
{
Public Dbset<Student> Students {get;set;}
}

Here DbContext responsible for retriving , inserting , updating Student class instaces in Database
39)What is the use of @model in views?

@model indicate that type of data that view expects

40) What is HandleError attribute in MVC ?

Using HandleErrorAttribute we can handle exceptions at actin method level , it is like below
[HandleError (ExceptionType = typeof(****) , view = "GenerateError")]
Public ActionResult Home()
{
return view()
}
If error exist in action method it will display GenerateError view 

If you apply same thing at controller level same thing apply to action methods in controller 

41) How to Enable customerrors in MVC ?

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error">
      <error redirect="~/Error/NotFound" statusCode="404" />
    </customErrors>
</system.web>
we have three modes 

On : Enabled custom error handling , display custom error page

Off :Disabled custom error handling , default page

RemteOnly :  Enabled custom error handling , but only from remote machine where application hosted

42)Health monitoring logging mechanisms  in MVC ?

If you want you can use EventLog class for mainatain application log,

Another way logging and better option is health monitoring enabled to the application.
-using this not only logging the exceptions , we can maintain application start and stop timing's
-Security events like number of failures in authorization
-Maintain exception details and validation details

For this we need enable settings in webconfig file
<healthMonitiring enabled="true">
<eventMappings>•••<\eventMappings>
<providers>....</providers>
<rules>...</rules>
<\healthMoniotiring>

43)How to generating URL's dynamically in MVC?

-Using UrlHelper.Action methods 
-Action methods has different overloads. 

var url=Url.Action("Branch" ,"GetDetails" , new {branch="CSE"});

in above syntax 
"Branch" is action method 
"GetDetails" is controller name 
branch is the additional parameters 

44)What is the use of name parameter in MapRoute method in MVC?

-name parameter is associated with route in which is combination of action methods , controllers and additional parameters.

ex: 
routes.MapRoute(
name:ViewDetails ,
template: "{controller = GetDetails}/{action = Branch}/{CSE}"
);


If we are using above mentioned route ("GetDetails/Branch/CSE") , rather than using entire you can "name" parameter in MapRoute path.

var url=Url.Action("ViewDetails" , new {branch="CSE"});

45)What is [FromHeader] attribute in MVC?

This attribute helps  to modelbinder to choose binding sources for the parameters.
if you mentioned above attribute Binder take parameters from request headers.

Public ActionResult GetDetails ([FromHeader] string rno)
{

}
Like above having different attributes in MVC  [FromRoute],[FromForm],[FromHeader],[FromBody]

46)How to customize data annotations attributes with error messages in MVC?

 Customize using ErrorMessage property 
[Required(ErrorMessage="RollNumber Required")]


47)What is common convention for layout in MVC?

Prefixing '_' (Underscore) is the common convention

Underscore differentiating normal layouts from standard views 

48) What is RenderBody() method in MVC views?

@RenderBody() method presents in Layout page <body> tag

This method instruction to templating engine to render content from other views.


49) What is the use of sections in MVC?

Sections are like placeholders in MVC , using to display different sections in one page.

If you want to display your web page content in different columns

@section  RightSidebar
{
//content
}

section content not rendering with @RenderBody() method. 

50)What is @RenderSection() method in MVC?

@RenderSection() is used for rendering section content into the layout page.

<div>
@RenderSection("RightSideBar",required:true)

required:true throwing an error if section files not present. 

51) What is the difference between sections and patialviews in MVC?

-Partial views are reusable views used in more than one view 
-Able to bind modeldata to partial view

-sections are like placeholders in masterpage 
If you want you can enable  or disable sections 
-sections are most probably used for rendering scripts , css files 

52) What is childactions , Do we have same in ASP.NETCore?

action method that could be invoked from the view is known as childactions , Childactions concept violating MVC pattern so that ASP.NET Core not having this.

53) What is the use of _ViewImports.cshtml in ASP.NET MVC Core?

- This file contain directives which are common to all the views in the folder.
-Instead  of adding directives to all the views , you can add here 

54) What is the use of _ViewStart.cshtml in ASP.NET MVC Core?

-This file contain common code , Every view in the folder before starting its execution using _ViewStart.cshtml  code
-Its contain razor code to set the layout for the views . If you want to override in view, yes you can.

@{
Layout = "_layout";
}

_ViewStart.cshtml not running for partial views , layouts only running for fullviews. 


Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

1 comment: