.Net MVC Interview Day -1

November 14, 2018 0 Comments A+ a-

ASP .Net

1. What is MVC (Model view controller)?

  • It stands for Model View Controller.
  • MVC framework is used to develop web application.
  • This framework developed by Microsoft on 2007.
  • MVC is an architectural pattern that can be separate tree main component such as Mode, View and Controller.

Authentication and Authorization in MVC Framework

May 03, 2018 0 Comments A+ a-

ASP .Net
In this we will discuss about the ASP.NET Roles and Membership API from MVC perspective. We will try to see how the default Roles and Membership provides can be used for authentication and authorization in an MVC application. We will also see how we can implement custom forms authentication in an ASP.NET MVC application.

AntiForgeryToken in MVC Framework

March 27, 2018 0 Comments A+ a-

ASP .Net

AntiForgeryToken

  • AntiForgeryToken is a great feature in ASP.NET MVC framework.
  • It generates a hidden field in form and valid value in cookies that is validated when the form is submitted to server.
  • It protect your application against cross site request forgery.

What is Cross Site Request Forgery?

  • Cross Site Request Forgery is a one type of attack.
  • It defined as a forgery request or fraud request, which comes on an authenticated site from cross site and is treated as an authenticated request.
  • The impact of CSRF attack is limited of the capabilities exposed by the vulnerable application.

Client Side Validation in MVC Framework

March 26, 2018 0 Comments A+ a-

ASP .Net

Client Side Validation

  • ASP.NET MVC framework also supports client side validation by using jqyery.
  • It will validate data immediate and display the error message in browser.
  • Validation should now happen on the client without a round trip to the server.
  • If the client disables javascript in the browser, then client side validation does not work but server side validation will continue to work as normal.

Custom Validation in MVC

March 25, 2018 0 Comments A+ a-

ASP .Net

Custom Validation

Validation attributes are a way to configure the model. Some validation rules are implemented based on your business. Your business rules might not be data data annotations validation. You need to implement for new business rule in your MVC application. This case you can go to custom validation.

Data Annotations in MVC Framework

March 23, 2018 0 Comments A+ a-

ASP .Net

Data Annotations

  • Data validation is a basic needed for developing web application.
  • In MVC framework provide DataAnnotation for data validations.
  • You can apply validation to web component by using data annotation attribute classes to model class properties.
  • These classes are present in System.ComponentModel.DataAnnotation namespace.
  • It help you to define the rules to the model properties for data validation and displaying appropriate messages to end users.

ValidationSummary in MVC Framework

March 22, 2018 0 Comments A+ a-

ASP .Net

ValidationSummary

  • ValidationSummary is a extension method of helper classs.
  • This can be used to display a consolidate error message for all the fields in view.
  • It can also be used to display custom error message on the screen.

Customize Validation in MVC Framework

March 20, 2018 0 Comments A+ a-

ASP .Net

You have learned how to implement validation in a view in the presious section.
In this section you will learn about How to customize the data validation in MVC framework.

ValidationMessage

  • HTml.ValidationMessage() is an extension method in helper class.
  • It used for displays a validation messageif an error exists for the specified field in the ModelStateDictionary object.
  • This is a loosely typed method.

ValidationMessageFor

  • This is also used to display the error message in MVC application.
  • HTml.ValidationMessageFor() is an extension method in helper class.
  • This is a strongly typed method.
  • It used for displays a validation messageif an error exists for the specified field in the ModelStateDictionary object.

Data Validation in MVC Framework

March 19, 2018 0 Comments A+ a-

ASP .Net
In this section all about validation, You will learn How to implement data server side validation and client side validation in MVC framework.
I will also talk about custom validation and cross site request forgery in this section.

Data Validation in MVC

MVC framework provide a lots of way to implement validation in form. Let's see the below validation.

Model Binding in MVC Framework

March 18, 2018 0 Comments A+ a-

ASP .Net

Model Binding

In this topic, We discuss about model binding in MVC framework.
Action Verbs are used to manipulate the action method based Http Request and Response. Now MVC framework will process the data and send to action method base on the Action Verbs. HttpGet Action versbs is retrieve the information from server but HttpPOST is post the data to server. While user is posting the data to action method by using model binding.

Html.ActionLink in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.ActionLink

You learn on this topic for How to create href link in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide one extension methods for generate link.
  • Html.ActionLink()

Html.Display and Html.DisplayFor in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.Display and Html.DisplayFor

You learn on this topic for How can you create string literal in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate hidden field.
  • Html.Display()
  • Html.DisplayFor()

Html.Editor and Html.EditorFor in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.Editor and Html.EditorFor

You learn on this topic for How can you create html elements based on the model properties type in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate hidden field.
  • Html.Editor()
  • Html.EditorFor()

Html.RadioButton and Html.RadioButtonFor in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.RadioButton and Html.RadioButtonFor

You learn on this topic for How can you create input type radio button in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate hidden field.
  • Html.RadioButton()
  • Html.RadioButtonFor()

Html.CheckBox and Html.CheckBoxFor in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.CheckBox and Html.CheckBoxFor

You learn on this topic for How can you create input type checkbox field in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate hidden field.
  • Html.CheckBox()
  • Html.CheckBoxFor()

Html.Hidden and Html.HiddenFor in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.Hidden and Html.HiddenFor

You learn on this topic for How can you create hidden field in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate hidden field.
  • Html.Hidden()
  • Html.HiddenFor()

Html.Password and Html.PasswordFor in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.Password and Html.PasswordFor

You learn on this topic for How can you create password field in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate text field.
  • Html.Password()
  • Html.PasswordFor()

Html.DropDownList and Html.DropDownListFor in MVC Framework

March 12, 2018 0 Comments A+ a-

ASP .Net

Html.DropDownListand Html.DropDownListFor

Helper class provide the below two extension for generating the dropdown list in a Razor view.
  • @Html.DropDownList()
  • @Html.DropDownListFor()

Html.TextBox and Html.TextBoxFor in MVC Framework

March 12, 2018 0 Comments A+ a-

ASP .Net

Html.TextArea and Html.TextAreaFor

HtmlHelper class provide two extension method for generate textarea field in MVC Framework.
  • Html.TextArea()
  • Html.TextAreaFor()

Html.TextBox and Html.TextBoxFor in MVC Framework

March 12, 2018 0 Comments A+ a-

ASP .Net

Html.TextBox and Html.TextBoxFor

You learn on this topic for How can you create text field in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate text field.
  • Html.TextBox()
  • Html.TextBoxFor()

Html.Label and Html.LabelFor in MVC Framework

March 11, 2018 0 Comments A+ a-

ASP .Net

Label in MVC Framework

You learn on this topic for How can you create label element in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate Label element.
  • Html.Label()
  • Html.LabelFor()

HTMLHelper in MVC Framework

March 10, 2018 0 Comments A+ a-

ASP .Net

HTML Helper

  • Now time build your own form in razor engine. In this topic we discuss the formbuild by using HTMLHelper class in MVC framework.
  • HTMLHelper is a class which contains different methods that use to create HTML controls in MVC View.
  • It also generates html elements by using the model object and this is called Strogly Typed HtmlHelper.
  • It able bind to display the value of model in the format of html elements.
  • It is only for design UI in MVC View.

Razor Engine in MVC Framework

March 09, 2018 0 Comments A+ a-

ASP .Net

Razor Engine

MVC Framework by default provide Razor View Engine and ASP .Net MVC support Web Form Engine.
Razor View Engine is responsible for rendering the view into HTML form to the browser response in MVC application.
Now ASP .Net MVC is open source so you can use some other third party engine in your MVC application such as Spark.
Let us discuss the some advantages of Razor View Engine.

Pass Data to PartialView in MVC Framework

March 09, 2018 0 Comments A+ a-

ASP .Net

Pass Data to PartialView

While the partial view is instantiated, Its own copy of a ViewDataDictionary object is available with the parent view.
So that partial view can access the parent view's data.
If you try to change the data in ViewDataDictionary, it will not affected in parent view.

ViewModel in MVC Framework

March 08, 2018 0 Comments A+ a-

ASP .Net

ViewModel

  • ViewModel allows to transfer the custom model/complex data from controller to view.
  • You must be create a strongly typed View which is using the data model List.
  • ViewModel properties are represented as Label, Display etc in the View.
  • ViewModel can have validation rules using data annotation.
  • ViewModel Can have multiple objects from different models or data source.
  • It is easy to rendering and maintenance.
There is no such different between ViewModel and Model. Only ViewModel is used for transfer the data between Controller and View.

TempData in MVC Framework

March 08, 2018 0 Comments A+ a-

ASP .Net

TempData

  • TempData is a dictionary object and it is property of controllerBase class.
  • It requires typecasting for the complex object.
  • TempData is used to pass data between two consecutive requests.
  • TempData only works during the current and subsequent request.
  • TempData is introduced in MVC 1.0 but It also works with MVC 1.0 and above.
   
public TempDataDictionary TempData { get; set; }
This properties define under ControllerBase class.

ViewBag in MVC Framework

March 08, 2018 0 Comments A+ a-

ASP .Net

ViewBag

  • ViewBag can be used for transfer the data from controller to view and even view to view.
  • ViewBag is a dynamic feature property of controllerbase class which was introduced in C# 4.0.
  • It not requires typecasting for the complex object to read the data.
  • It not require the null check
  • It's value becomes null when page is redirected.
  • It's live only during the current request.
  • It is slower than ViewData.
  • ViewBag is introduced in MVC 3.0 and available in MVC 3.0 and above
   
public dynamic ViewBag { get; }
This properties define under ControllerBase class.

ViewData in MVC Framework

March 08, 2018 0 Comments A+ a-

ASP .Net

ViewData

  • ViewData also used to passing/storing data from controller to view.
  • If you initialise objects in ViewData, those objects become accessible in the view.
  • ViewData is a dictionary and It derived from ViewDataDictionary class. You can access by "Key/Value" pair.
  • It requires typecasting for the complex object.
  • You must be check for null values to avoid error.
  • It's value becames null when page is redirected.
  • It's live only during the current request.
  • ViewData is Faster than ViewBag.
  • ViewData is introduced in MVC 1.0 but It also works with MVC 1.0 and above.
   
public ViewDataDictionary ViewData { get; set; }
This define under ControllerBase class.

Pass Data from Controller to View in MVC Framework

March 08, 2018 0 Comments A+ a-

ASP .Net

Pass Data from Controller to View

We will discuss about pass data from controller to view in MVC framework.
There is different ways for transfer data from controller to view or view to controller.
Way of Transfer Data
  • ViewBag
  • ViewData
  • ViewModel
  • TempData

Partial View in MVC Framework

March 07, 2018 0 Comments A+ a-

ASP .Net

Partial view:

Right now we will discuss about the partial view . This is the most importment part of MVC Framework. We can effective way of breaking up large views ito smaller components. All each smaller component make as partial view. We can combined together all these small piece of code or partial view as per your requirement. So It can allow us to reusable code and reduce the duplication of code in MVC application.
There is no huge difference between a partial view and a normal view, only rendered differently. Partial view always render inside the normal view .

Layout View in MVC Framework

March 07, 2018 0 Comments A+ a-

ASP .Net

Layout View

  • Before start this session we will discuss about ASP .NET Webform application. In ASP .NET web from We are used the master page for the theme design or common layout for all the webform.
  • Similarly, In ASP .NET MVC framework provide the Layout view to create a common template for all the view.
  • ASP.NET MVC introduced a layout view which contains these common UI parts such as logo, header, left/right side bar, footer etc.
  • All these common parts no need to write the same code in every page. So Layout view define the common component and every view are accessing the layout view.
  • Layout view gives standard look and feel like a template for razor views.
  • It should be contain inside shared folder.

View in MVC Framework

March 06, 2018 0 Comments A+ a-

ASP .Net

View :

  • View is the user interface layer in MVC framework.
  • View contains UI logic of application such as from details, form component details, a template etc and produces a response for the browser.
  • View receives data from from the controller and represent it to the browser for display.
  • It is rendering the static or dynamic content on the browser by the help of View Engine.

Database Model in MVC Framework

March 06, 2018 0 Comments A+ a-

ASP .Net

Database Model :

In this session we will discussed about the data binding from database.
MVC application retrieves the database table data and display on the view.
Let's see the below example.
Step - 1
First step you need to create your own table.
 
CREATE TABLE [dbo].[tbl_Employee](
 [ID] [int] NOT NULL,
 [Name] [varchar](50) NOT NULL,
 [Location] [varchar](50) NOT NULL,
 CONSTRAINT [PK_tbl_Employee] PRIMARY KEY CLUSTERED 
(
 [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Model in MVC Framework

March 05, 2018 0 Comments A+ a-

ASP .Net

Model:

  • Model is a collection of class, There you can be working with data and business logic.
  • Model can able to maintain the data of the application.
  • It is also used to interact with database.
  • All the model class contains inside the Model folder in MVC application.
  • All the properties of the model always public.
  • Let's see the below snippet code for create a model in MVC application.

Create a Custom Filter in MVC Framework

March 05, 2018 0 Comments A+ a-

ASP .Net

Custom Filter:

ASP .NET MVC, User can be create his\her own custom action filter.
For example user wants maintain loging for each method details in application.So this you can be write the same logic over and over.
This approch have lots of disadvantages such as repeatly write same logic, Time waste, man power waste, diffcult to maintain the code, maintenance cost is more etc.
In ASP .NET MVC, you can create your own custom filter and call it over the controller or an action method.

Exception Filter in MVC Framework

March 04, 2018 0 Comments A+ a-

ASP .Net

Exception Filter :

  • In ASP .Net application, Error handling is done by using TRY.. CATCH block in local level or application events in global level But in ASP .NET MVC comes with some built-in support for exception handling through Exception Filter.
  • Exception filters can be used for tasks such as logging or displaying an error page/message while there is an unhandled exception thrown somewhere in action method or filter.
  • The exception filter attribute can be applied over an action or a controller or a global level. While you apply the filter at the global level then It will handle the exception raised by all the controller. Similarly If you applied the filter over a controller then It will handle the exception raised by all the action method in that specific controller.
  • The exception filter can be capable to handle exception raised by the MVC filters.

Result Filter in MVC Framework

March 04, 2018 0 Comments A+ a-

ASP .Net

Result Filter

  • This filter can executed before and after a ActionResult object.
  • It can perform additional processing of the result like modifying the HTTP response.
  • Result Filters are very similar to the Action Filters. in MVC. Only These are executed before and after a view result is executed.
  • It implemented from the IResultFiler interface. This interface also looks similar to the IActionFilter.
  • This interface provides two methods OnResultExecuting and OnResultExecuted which will be called before and after the action result respectively.

Action Filter in MVC Framework

March 03, 2018 0 Comments A+ a-

ASP .Net

Action Filter :

Action filters are used to implement logic that gets executed before and after a controller action executes.
This filter can perform additional processing like providing extra data to the action method or canceling execution of the action method.
This attributes can be applied to an action method or an entire controller. If action filter applied to controller then It will be applied to all the action methods in that controller.

Authorization Filter in MVC Framework

March 02, 2018 0 Comments A+ a-

ASP .Net

Authorization Filter:

Authorization filters allow you to perform authorization or validating properties tasks of the request for an authenticated user.
In ASP.NET MVC 4 introduced a new feature such as AllowAnonymous attribute. This attribute allows to access anonymous users for specific controller or action method.
In ASP.NET MVC 5 has improvements around authentication because it includes new authentication filters and ASP.NET Identity framework.

Filters in MVC Framework

March 01, 2018 0 Comments A+ a-

ASP .Net

Filters:

in MVC Framework, Filter is a one type of custom class, There you can write your own custom logic to execute before or after an action method executes or View render. Filters can be applied to an action method or controller in a declarative or programmatic way. Declarative means by applying a filter attribute to an action method or controller class and programmatic means by implementing a corresponding interface.
The ASP.NET MVC framework supports four different types of filters. Please follow the below details.
  • Authorization Filter
  • Action Filter
  • Result Filter
  • Exception Filter

Action Selector

February 28, 2018 0 Comments A+ a-

ASP .Net

Action Selector:

Action Selectors are the attributes that can be applied to the action methods in MVC application.
Those are helping routing engine to select the appropriate action method from MVC controller to handle the specific request.
There are three types of action selectors attributes.
  • ActionName
  • NonAction
  • ActionVerbs

Action Method in MVC Framework

February 27, 2018 0 Comments A+ a-

ASP .Net

Action method:

Now You will discuss about the action method of controller.
  • Action method must be public.
  • It cannot be private or protected.
  • It cannot be overloaded and static method.
  • It cannot be an extension method.
  • It cannot have open generic types.
  • It contain ref or out parameters
  • It can process the logic and Error handling.

Controller in MVC Framework

February 26, 2018 0 Comments A+ a-

ASP .Net

Controller :


  • In ASP.NET MVC, a Controller handles any incoming URL request and responsible for returning the response to that request.
  • It is used to define and group a set of actions.
  • allowing common sets of rules such as routing, caching, authorization etc to be applied on controller or action.
  • Incoming requests are mapped to actions through routing.
  • It inherit from Microsoft.AspNet.MVC.Controller namespace.
  • Every controller class name must suffix with a word "Controller".
  • Controller is processed incoming request by the help of actions.

Advance Routing in MVC Framework

February 25, 2018 0 Comments A+ a-

ASP .Net

Multiple Routes:

Route customization is an advance topic. In this session we will look at customize the multiple routing in MVC application. You can configure the multiple routes using Map Route extension method in RouteConfig.cs. This method needs at least two parameters such as route name and URL pattern and URL parameter is optional. If you need to pass some value to action using parameter then parameter is mandatory.
While requested URLs comes to application. It is start compared to route patters in order the pattern sequence in the route dictionary or order of added the route in RouteConfig.cs file. If request URLs matched with first URL pattern of the route dictionary, then it will call specified controller and action. In case if URL is not matched with pattern of the route dictionary, then it will call default map route method and executed the default controller and action. Similarly you can able to your own route map in routeconfig.cs file.
Example -1
Route Configuring:
 
       public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");           
   routes.MapRoute(
                name: "EmployeeDetails", 
                url: "EmployeeDetails/{id}",
                defaults: new { controller = "Employee", action = "Details", id = UrlParameter.Optional }
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

Attribute Routes:
 
       [Route("EmployeeDetails/{id}")]
public ActionResult EmployeeDetailsbyID(int id)
  {
  }
How to enable Attribute Routes in MVC application ?

  • You must have enable attribute route in routeconfig.cs file. 
  • It must be enable before the default route.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
            );
        }

Pass Multiple Parameter to MVC Action:

Now we will discuss multiple parameter pass to action. you can define the rules in routeconfig.cs file and also attribute route.
For example, the following route applies a multiple parameter pass to action.
Route Configuring:
Example - 2
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute( 
   "EmployeeByJoinDate",
   "Employee/Join/{year}/{month}",
   new { controller = "Employee", action = "EmployeeByJoinDate"}
        }
Attribute Routes:
In this case you can also apply the rules in controller on attribute level.
Example - 3
      
[Route("Employee/Join/{year}/{month}")]
public ActionResult EmployeeByJoinDate(int year, int month)
  {
  }
Above both example will work as same.

Route Constraints:

It will restrict the value of parameter by configuring route constraints and attribute route constraints.
Route Configuring:
Example - 4
public static void RegisterRoutes(RouteCollection routes)        {
            routes.MapRoute( 
   "EmployeeByJoinDate",
   "Employee/Join/{year}/{month}",
   new { controller = "Employee", action = "EmployeeByJoinDate"},
   new { year = @"\d{4}", month = @"\d{2}"}
        }
Attribute Routes:
Example - 5
      
[Route("Employee/Join/{year:regex(\\d{4})}/{month:regex(\\d{2})}")]
 public ActionResult EmployeeByJoinDate(int year, int month)
  {
  }
ConstraintDescriptionExample
alphaMatches uppercase or lowercase Latin alphabet characters (a-z, A-Z){x:alpha}
boolMatches a Boolean value.{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value.{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(6)}
{x:length(1,20)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}
rangeMatches an integer within a range of values.{x:range(10,50)}
regexMatches a regular expression.{x:regex(^\d{3}-\d{3}-\d{4}$)}

Route Prefixes:

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute.
Use a tilde (~) on the method attribute to override the route prefix.
Example - 6
[RoutePrefix("Employee/Details")]
public class EmployeeController : Controller
{
// GET Employee/Details
    [Route("")] 
    public IEnumerable EmployeeDetails() { ... }
 
//Employee/Details/12
    [Route("{id:int}")] 
    public EmployeeModels EmployeeDetailsByID(int id) { ... }

//employeemodels/Employee/Join/2018/02
    [Route("~/Employee/Join/{year:regex(\\d{4})}/{month:regex(\\d{2})}")]  
    public HttpResponseMessage EmployeeByJoinDate(int year, int month) { ... }
}

Warm up

  • Configure the multiple routes using Map Route extension method in RouteConfig.cs.
  • Pass multiple parameter to action by using Route Configuring or Attribute Routes.
  • Restrict the value of parameter using Route Constraints on Route Configuring or Attribute Routes.
  • You can set a common prefix for an entire controller by using the [RoutePrefix] attribute.
  • Use a tilde (~) on the method attribute to override the route prefix.