Archive

Archive for the ‘MVC’ Category

Routing in MVC

July 19, 2015 Leave a comment

ASP.MVC routing module is responsible for handling incoming browser request (http request) and map to MVC controller action method.

Routing Module

  • When first time request come to the MVC application, it check for ‘Route Table’ since it is first time request to the application it fills the ‘Route Table‘.
  • Once the ‘Route Table’ is updated then request goes to ‘URL Routing Module’. If the incoming request not first one then it directly goes to ‘URL Routing Module’.
  • And this ‘Routing table’ is created at Application_Start event.
    “RegisterRoutes(RouteTable.Routes);”

routes.MapRoute(
“Default”,                                              // Route name
“{controller}/{action}/{id}”,                           // URL with parameters
new { controller = “Home”, action = “Index”, id = “” }  // Parameter defaults
);

Name: Default
URL Pattern: {controller}/{action}/{id}
Values: new { controller = “Home”, action = “Index”, id = “” }

  • Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
  • From ‘URLRoutingModule’ it goes to ‘MVCHandler’ as RequestContext object, the ‘RouteData’ object is used as RequestContext object.
  • In ‘MVCHandler‘ Controller instance will be created and it calls the ‘Execute‘ method of the controller class.
  • Once ‘ActionMethod‘ executed result will be sent back to view as response object.

Note:-
Routing module is responsible till it calls the matching ActionMethod.

 

Advertisements
Categories: MVC Tags:

Enable client side validation

July 19, 2015 Leave a comment

By default client side scripting disabled by default. To enable Client side scripting in MVC you need to follow the below 2 steps.

Step 1:

To Enable Client Side validation in web.config

<appSettings>
<add key=”ClientValidationEnabled” value=”true”/>
<add key=”UnobtrusiveJavaScriptEnabled” value=”true”/>
</appSettings>

Step 2:

– Include reference of javascript files in the masterpage
– Avoid adding reference in each and every View page

Add the following references in Masterpage

<script src=”~/Scripts/jquery-1.8.2.min.js” type=”text/javascript”></script>
<script src=”~/Scripts/jquery.validate.min.js” type=”text/javascript”></script>
<script src=”~/Scripts/jquery.validate.unobtrusive.min.js” type=”text/javascript”></script>

The order of adding reference are also important.

Now we can able to validate in client side by avoiding round trip to server side.

Filters in MVC

July 18, 2015 Leave a comment

Using filters you can inject you business logic or business rules into the Action Methods or to entire controller. Business rules can be applied before and after the action method gets executed.

Some of your action filters 
   1) OutputCache

– It will catch the out put of action method up to certain time period.
CacheProfiler > Define the cacheProfiler in web.config  and call it in controller action method. So that when you change it in later you no need to redeploye the code.

   2) HandleError

– Handles the error if any error occurs while executing the action method.
– No need to add separately to each action method or Controller since HandleErrorAttribute is added globally in Global.asax page.
<customErrors mode=”On”/> in root web.config of root application.
– we can also create common Exception Controller and specify the error code and the controller to redirect under customErrors of web.config file.
   3) Authorize

  • Allow/Restrict  particular user(or)roles.
  • By default all action methods are accessible all the anonymous and authenticated users in Mvc.
  • To allow only authenticated to access the Action Method use [Authorize] attribute.

   4) ChildActionOnly

ChildActionMethod Invoked by making child request from view using ‘Action()’, ‘RenderAction()’ html helper.
– When the Action Method is decorated with [ChildActionOnly] we can’t access it through URL. If you try to access it will throw you ‘ChildActionMethod can be accessible only through the child request’
ChildActionOnly typically associated with partial view but this is not compulsory.
– [NonAction] different from [ChildActionOnly], [NonAction] attribute can not be called through URL or through ‘Action()’, ‘RenderAction()’ html helper.
– Can cache portion of view through ChildActionMethod.
5) RequireHttps

– Force the actionmethod to execute and display it  through ssl layer
– So that data that is transmitted are secure.

you can create your own custom filters. In MVC 4.0 you have 4 types of custom filters

  1. Authorization Filter – Implements IAuthorizationFilter interface.
  2. Action Filter – Implements the IActionFilter interface.
  3. Result Filter – Implements the IResultFilter interface.
  4. Exception Filter – Implements the IExceptionFilter interface.

Filters will be executed in above order. If you want to control the order in which filters of same type are executed using filter’s Order property. System.Web.Mvc.FilterAttribute  is the base class for all the Filter actions, when ever you implement custom filter attribute you should inherit this base class and any one or more above mention filters.
ActionFilterAttribute this base class inherits IAction and IResult interfaces

The base ActionFilterAttribute class has the following methods that you can override:
OnActionExecuting – This method is called before a controller action is executed.
• OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.

For More Refer here (Click Here)

Different ways of Parameter can pass in Controller

July 14, 2015 Leave a comment

When you submit the data to action method of controller it can be done through the parameter. There are 4 different ways of parameter you can pass

1) Request object
2) FormCollection
3) using predefined datatypes
4) Custom datatype

When ever request object submit the data([HttpPost]) it will check with the action method’s parameter type based on that it will pass the parameter

1) Form Collection

It holds the value as key/value pair
While send the data back to the controller(Request object) we can send as FormCollection object.
If you specify as FormCollection type in action method signature you will get the user submitted value as key/value pair
Key contains control name and value will hold the value of the control.

Example:-
[HttpPost]
public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
{
foreach (string _formData in formCollection)
{

}

return View();
}

2) Request Object

It holds the values as Name-Value pairs.
While send the data back to the controller(Request object) we can submit the form as Post method.
If you are not specify action method signature and using Request[“ControlName”] you can get the value.

Example:
[HttpPost]
public ActionResult SubmitFormWithRequestObject(FormCollection formCollection)
{
int i=convert.ToInt32(Request[“txtAge”].toString())

return View();
}

3) Predefined parameter

Name of the control in View must be the variable name of parameter with data type.
We can define the parameter with the corresponding data type (int, string,…) that control will get as input.
For each control we will pass the separate parameter in the action method.

Example:
[HttpPost]
public ActionResult SubmitFormWithSimpleParameter(string txtName, string txtAddress, int txtAge, date txtDOB)
{
// Do some codes;

return View();
}

4) Custom Parameter

Custom data type can be passed as parameter
In the action method we passed model as parameter

Example:
[HttpPost]
public ActionResult SubmitFormWithSimpleParameter(PersonalInfo info)
{
// Do some codes;

return View();
}

Categories: MVC Tags:

Security issue in MVC delete using hyperlink

March 13, 2015 Leave a comment

In Stephen Walther post, he mentioned security issue in deleting the record through GET request. In MVC hyperlink will use GET request to delete a record, so any one can able to access the record just by passing the id of record.

Example:-

http://www.kethare.in/employee/delete/1

In the above example we are using GET request to delete the employee record by clicking the corresponding delete hyperlink of the employee. So the value that you are passing is known and any one who knows the delete URL can have possibility of deleting the record which is not advisable.

Stephen Walther provide solution to bypass this issue is using client side scripting (AJAX(or) JQUERY, JavaScript…)

System.Data.Entity.Infrastructure missing Namespace

December 29, 2014 Leave a comment

install the EntityFramework NuGet package which will setup everything for you .

Go to

menu “Tools”-> Library Package Manager –>  Package Manger Console
and typing there:
PM> install-package EntityFramework

That’s it. All errors disappeared.

Categories: MVC

Cross-Origin Request Blocked: ASP.NET MVC

November 25, 2014 Leave a comment

Problem:

While i try to call the Web-Api service through JQuery, i am unable to receive the complex type collection in my client side, it throws error message in my console table of my browser as below.

Cross-Domain-Policy

Fix:

Add the below code in WEB-API project web.config file

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <!-- Adding the following custom HttpHeader will help prevent CORS from stopping the Request-->
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

 

For source and more detail click here

%d bloggers like this: