Posts

Showing posts with the label MVC

Step by step migration of ASP.NET Core 2.2 to 3.1

In order to upgrade/migrate asp.net core version to 3.1 following steps to be perform.
Download and install Visual Studio 2019 version 16.4 or higher.Download and install .NET Core 3.1  https://dotnet.microsoft.com/download/dotnet-core/3.1Upgrade the projects of solution to .NET Core 3.1 , because ASP.NET Core 3.1 requires it.Update existing Nuget packages to a version compatible with ASP.NET Core 3.1 in each projectUse IHost interface from a IHostBuilder instead of building and running a IWebHost from a IWebHostBuilder in Program.cs public static IHostBuilder CreateWebHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseKestrel() .UseSerilog() .UseStartup<Startup>(); }) Change AddMvc method has been replaced by AddControllers in Startup.cs of each projects.In Startup.cs,UseMvc method to be replaced by…

Dependency injection in ASP.NET Core MVC controller explained step by step

ASP.NET Core MVC controllers should request their dependencies explicitly via their constructors. In some instances, individual controller actions may require a service, and it may not make sense to request at the controller level. In this case, you can also choose to inject a service as a parameter on the action method.

With ASP.NET 5 MVC6, we get a feature called dependency injection baked right into the framework for us.

Dependency injection is a technique that follows the Dependency Inversion Principle, allowing for applications to be composed of loosely coupled modules. ASP.NET Core has built-in support for dependency injection, which makes applications easier to test and maintain.

ASP.NET Core's built-in support for constructor-based dependency injection extends to MVC controllers. By simply adding a service type to your controller as a constructor parameter, ASP.NET Core will attempt to resolve that type using its built in service container. Services are typically, but not alw…

Introduction of Asp.net MVC Basics for beginners

MVC is an architectural pattern which separates the representation and user interaction.
It's divided into three broader sections,

ModelViewController. 
Below is how each one of them handles the task.
View : The View is responsible for the look and feel.
Model: Model represents the real world object and provides data to the View.
Controller: The Controller is responsible for taking the end user request and loading the appropriate Model and View.

Advantages of ASP.NET MVC


Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.Complex applications can be easily managedSeparation of concerns. Different aspects of the application can be divided into Model, View and Controller.ASP.NET MVC views are light weight, as they do not use view-state.It provides extensive support for URL Routing that helps to make friendly URLs (means friendly for human as well as Search Engines).Support for existing ASP.NET features like membership and roles, authentication and authoriz…

Security Exception in ASP.NET on shared hosting environment [solved]

When i was trying to host my newly developed website on shared server and i stuck with following exception

Security Exception in ASP.NET

[SecurityException: Request failed.] System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) +165 System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) +100 System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandleInternal rmh, Object assemblyOrString, SecurityAction action, Boolean throwException) +284 System.Security.CodeAccessSecurityEngine.CheckSetHelper(CompressedStack cs, PermissionSet grants, Permissio…

Dependency injection in MVC controller step by step

ASP.NET Core MVC controllers should request their dependencies explicitly via their constructors. In some instances, individual controller actions may require a service, and it may not make sense to request at the controller level. In this case, you can also choose to inject a service as a parameter on the action method.

With ASP.NET 5 MVC6, we get a feature called dependency injection baked right into the framework for us. 

Dependency injection is a technique that follows the Dependency Inversion Principle, allowing for applications to be composed of loosely coupled modules. ASP.NET Core has built-in support for dependency injection, which makes applications easier to test and maintain.

ASP.NET Core's built-in support for constructor-based dependency injection extends to MVC controllers. By simply adding a service type to your controller as a constructor parameter, ASP.NET Core will attempt to resolve that type using its built in service container. Services are typically, but not al…

Asp.Net MVC page life cycle quick overview

There are seven main steps that happen when you make a request to an Asp.net MVC web applications.


Routing Asp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching system that matches the request’s URL against the registered URL patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. The default one calls the MvcHandler. The routing engine returns a 404 HTTP status code against that request if the patterns is not found in the Route Table. When application starts at first time, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table and this is setup in the Global.asax file of the application.


MvcHandler The MvcHandler is responsible for initiating the real processing inside ASP.NET MVC. MVC handler implements IHttpHa…

All about tempdata in Asp.Net MVC

Image
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, TempData can be used to maintain data between controller actions as well as redirects.

Note: Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors.

Let’s see how we can use TempData in a practical scenario to pass data from one controller action to another.


//Controller Action 1 (TemporaryEmployee)public ActionResult TemporaryEmployee() { Employee employee = new Employee { EmpID = "121", EmpFirstName = "Imran", EmpLastName = "Ghani" }; TempData["Employee"] = employee; return RedirectToAction("PermanentEmployee"); } //Co…

File extension validation using javascript in MVC

This is article which demonstrate the validation of allowed file extension for upload of files in MVC using javascript. In this article i have used validation for valid image format like Jpeg, Jpg,Gif and png image format. If users ties to upload any other file apart from above mentioned file then the javascript function will shows proper message to user to select appropriate files.

I have used html input file control for uploading of files in MVC application.

following is the html code for it.


<body> <div style="height:50px; padding-bottom:20px;"> @using (@Html.BeginForm("Create","FileUpload",FormMethod.Post,new{ enctype = "multipart/form-data"})) { <input type="file" id="file1" name="sdf" style=" margin-top:0px;" onchange="if( CheckExtention(this.value) ) {parent.ShowHideImage(true);this.form.submit();}" /> } </div> </body>
and following is the ja…

Asp.Net MVC best practices part 1

If you decided to develop the application using Asp.Net MVC application and. I am going to demonstrate you to follow the best practices in MVC to develop the robust web application. If you want to log the exceptions occurs in controllers you need to write try catch blocks in each action method. This approach is also not recommended because you need to write try catch block in each action method. To get ride of this you can handle exceptions and log each exception by using centralized approach. These approaches are as follows

Do not inherit the Controller base class directly to your ControllersCreate new base custom controller class which inherits the base controller classInherit created base custom controller class to your controllersFollowing is the sample code which demonstrate the above best practices


public class BaseController : Controller { }
In above code I have inherited the controller class to custom base controller class and below is the code to use this created custom…