European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: In HTML Tags Custom Attribute

clock April 18, 2022 10:41 by author Peter

In versions prior to ASP.NET MVC 3, you could not declare HTML attributes with dashes/hyphens, without creating a custom type that handled dashes for you. Most of you, who have used custom data attributes with dashes in MVC 1 and 2, must be familiar with the Compiler Error CS0746:


If you use attribute name e.g "data-name", you will see an error

error
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access

However in ASP.NET MVC 3, there is a trick that can be used to handle HTML attributes with dashes. Just use ‘underscores’ in your custom data attribute instead of ‘hyphens’. MVC 3 using the HTML helpers, automatically converts these underscores into dashes/hyphens
@Html.HiddenFor(Model => Model.PartnerId, new { ng_model = "PartnerId" })

BASIC
After view will be rendered then it'll be converted as shown below.
<input type="hidden" name="PartnerId" value="1", ng-model="PartnerId" />



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Showing Data Changes Using SQLDependency With SignalR In ASP.NET MVC

clock March 18, 2022 07:37 by author Peter

Here, I am using SQLDependency which notifies us when any changes are done to the data in the database. First, you have to add an empty MVC project and after that, add the SignalR Package which can be added by using NuGet Package Manager.

Add a Controller in your project.
public class HomeController : Controller  
    {  
        // GET: Home  
        public ActionResult Index()  
        {  
            return View();  
        }  
        public JsonResult GetMessages()  
        {  
            List<data> messages = new List<data>();  
            Repository r = new Repository();  
            messages = r.GetAllMessages();  
            return Json(messages,JsonRequestBehavior.AllowGet);  
        }  
    }

Now, add a new class and name it as Repository.
public class Repository  
    {  
        SqlConnection co = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["con"].ConnectionString);  
        public List<data> GetAllMessages()  
        {  
            var messages = new List<data>();  
            using (var cmd = new SqlCommand(@"SELECT [id],   
                [name],[adres] FROM [dbo].[userdata]", co))  
            {  
                SqlDataAdapter da = new SqlDataAdapter(cmd);  
                var dependency = new SqlDependency(cmd);  
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);  
                DataSet ds = new DataSet();  
                da.Fill(ds);  
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
                {  
                    messages.Add(item: new data  
                    {  
                        id = int.Parse(ds.Tables[0].Rows[i][0].ToString()),  
                        name = ds.Tables[0].Rows[i][1].ToString(),  
                        adres = ds.Tables[0].Rows[i][2].ToString()  
                    });  
                }  
            }  
            return messages;  
        }  
 
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e) //this will be called when any changes occur in db table.
        {  
            if (e.Type == SqlNotificationType.Change)  
            {  
                MyHub.SendMessages();  
            }  
        }  
    }

In Models folder, add a class and name it as data.
public class data  
   {  
       public int id { get; set; }  
       public string name { get; set; }  
       public string adres { get; set; }  
   }


Here, you have to add a SignalR Hub Class to you project and name it as MyHub.
[HubName("MyHub")]  
   public class MyHub : Hub  
   {  
 
       [HubMethodName("sendMessages")]  
       public static void SendMessages()  
       {  
           IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();  
           context.Clients.All.updateMessages();  
       }  
   }

Again, you have to add another class named OWIN Startup Class.
public class Startup  
   {  
       public void Configuration(IAppBuilder app)  
       {  
          // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888  
         app.MapSignalR();  
       }  
   }


View(Index)
@{  
    Layout = null;  
}  
 
<!DOCTYPE html>  
 
<html>  
<head>  
    <meta name="viewport" content="width=device-width" />  
    <title>Index</title>  
    <script type="text/javascript" src="~/Scripts/jquery-1.6.4.min.js"></script>  
    <script type="text/javascript" src="~/Scripts/jquery.signalR-2.2.2.js"></script>  
    <script type="text/javascript" src="/signalr/hubs"></script>  
    <script type="text/javascript">  
    $(function () {  
        // Declare a proxy to reference the hub.  
        var notifications = $.connection.MyHub;  
 
        //debugger;  
        // Create a function that the hub can call to broadcast messages.  
        notifications.client.updateMessages = function () {  
            getAllMessages()  
 
        };  
        // Start the connection.  
        $.connection.hub.start().done(function () {  
            alert("connection started")  
            //notifications.onconn();  
            getAllMessages();  
        }).fail(function (e) {  
            alert(e);  
        });  
    });  
 
    function getAllMessages()  
    {  
        var tbl = $('#messagesTable');  
        $.ajax({  
            url: '/Home/GetMessages',  
            contentType: 'application/html ; charset:utf-8',  
            type: 'GET',  
            dataType: 'html'  
        }).success(function (result) {  
            var a2 = JSON.parse(result);  
            tbl.empty();  
            $.each(a2, function (key, value)  
            {  
                tbl.append('<tr>' + '<td>' +value.id + '</td>' + '<td>' + value.name + '</td>' + '<td>' + value.adres + '</td>' + '</tr>');  
            });  
        })  
    }  
    </script>  
</head>  
<body>  
    <div>   
        <table id="tab">  
             
        </table>  
    </div><br/>  
    <div class="row">  
        <div class="col-md-12">  
            <div >  
                <table border="1">  
                    <thead>  
                        <tr>  
                            <th>id</th>  
                            <th>name</th>  
                            <th>address</th>  
                        </tr>  
                    </thead>  
                    <tbody id="messagesTable">  
 
                    </tbody>  
                </table>  
            </div>  
        </div>  
    </div>  
</body>  
</html>   




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Could Not Find A Part Of The Path... bin\roslyn\csc.exe

clock March 15, 2022 09:20 by author Peter

A fix to Roslyn issue when compiling in .NET Code.

Introduction
This is long existing issue, at least since VS 2015.  There are two possible fixes, one is updating the Roslyn to make the code work, another one is deleting Roslyn.  I prefer the latter and will introduce my solution.

The structure of this article:
    Introduction
    Problem
    Two Possible Fixes
        Update the Roslyn compiler
        Delete the Roslyn compiler
    My Fix

Problem
When running a MVC web application, we got this error message:

Possible Fixes
Search online, we saw two possible solutions in one thread: Could not find a part of the path ... bin\roslyn\csc.exe, the suggestions as below:
Update the Roslyn compiler 


Delete the Roslyn compiler,


 

My Fix
I prefer the latter one. This is my solution:
Search entire solution for Microsoft.CodeDom.Providers.DotNetCompilerPlatform


Search entire solution for Microsoft.Net.Compilers

Open Package Manager Console in Visual Studio:

Run the following command if any one of the above existing,
PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers


For ours, we run the first,

Recheck the result,

Microsoft.CodeDom.Providers.DotNetCompilerPlatform is gone,


Recompile and run, the app works.
Check the changes. In Packages.config,

In Web.config,



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Customer Error page In MVC 5.0

clock March 2, 2022 07:25 by author Peter

In this article, we will look at how to manually customize an error page in ASP.NET MVC 5.


MCV Introduction

The MVC architectural pattern separates the user interface (UI) of an application into three main parts.

Model

A set of classes that describes the data you are working with as well as the business logic.

View
Defines how the application’s UI will be displayed. It is pure HTML, which decides how the UI is going to look.

Controller
A set of classes that handles communication from the user, overall application flow, and application-specific logic

When an HTTP request arrives for an MVC application, that request gets routed to a controller, and then it is up to the controller to talk to either the database, the file system, or the model.

Why do we need a Custom Error Page?

We would just configure our custom error pages in one place and it would just work, no matter how/where the error was raised. In order to handle exceptions thrown by your action methods, you need to mark your method with the HandleError attribute. The HandleError attribute also allows you to use a custom page for this error.
Steps to be Followed

Step 1
Create a MVC application named “Http500Test”. For this demo, I have used VS 2019 and .NET version 4.7.2


The solution looks like this

Step 2
Create a Controller class file named “CustomerErrorUserController.cs”

[HandleError] attribute provided built-in exception filters. This attribute can be applied over the action method as well as the controller or at the global level.

At CustomerErrorUser/Index, this application will show error.cshtml as the view not found in Index but in the web.config file. The error statusCode="404" means that the file is not found and it means the controller name or controller action method name is the issue.

[HandleError] //If I put in this attribute and run, it will go to the Customized by a Default error page.

Step 3

Create a controller class named “ErrorController.cs”

I have added two action methods – NotFound() and UnhandledException().

Step 4
Go to View/Shared Folder; create two views named “NotFound.cshtml” and “UnhandledException.cshtml”


Put your own code in the NotFound.cshtml file by removing the existing code.

Put your own code in the UnhandledException.cshtml file by removing the existing code.

Step 5
Go to Web.config and. Add some code for “File Not Found” and “UnhandledException”

Output
http://localhost:63217/CustomeErrorUser

How to display UnhandledException?
I have added two lines of code in the About() action method in HomeController.cs

Now run this MVC app and click on “About”

Instead of redirecting to “UnhandledException.cshtml”, the app is showing error.cshtml file
How to show UnhandledException.cshtml?

Visual Studio, by default, is creating two cshtml files, i.e. _Layout.cshtml and Error.cshtml inside the Shared folder.

Since we are using [HanldeError] attribute, all the unhandled exceptions will be redirected to by default error page (Error.cshtml).

There was some boilerplate code left in the FilterConfig.cs when creating the project.

This creates a new instance of HandleErrorAttribute, which is applied globally to all of my views. With no customization, if a view throws an error while utilizing this attribute, MVC will display the default Error.cshtml file in the Shared folder.

Commenting this line out solved the problem and allowed me to use custom error pages for 500 errors.

Again run the application and click on “About”

 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Create ASP.NET Core MVC 6.0 Application?

clock February 21, 2022 08:46 by author Peter

Prerequisites
    Install Visual Studio 2022 updated version 17.0 or later.
    Install .NET SDK 6.0

Now let's start creating an ASP.NET Core MVC 6.0 web application.

Step 1 - Install Visual Studio
First, install Visual Studio 2022 in your system.

Step 2 - Open Visual Studio
Open Visual Studio 2022.

 

Step 3
Then click on Continue Without Code as shown in the following image


Step 4
Then from Visual Studio Menu, click on File -> New-> Project, as shown in the following image

Click on the New Project, then the following window appears as shown in step 5.

Step 5- Choose Project Template
You can see various project template types, choose the ASP.NET Core Web App (Model-View-Controller) .this project template creates the web application with Model, View and Controller (MVC), as shown in the following image.

After choosing the project template click on Next

Step 6 - Define Project Name and Location
In the project configuration window you will see the following options,

    Project Name
    Define any name for your project as per your choice. Here I have chosen project name as “Asp.NetCore6Demo”.

    Location
    Choose the location to save the project files on your hard drive of the system. I have chosen the Project/VS folder of the E drive of the system.

     Solution Name
    Solution name is auto-defined based on the project name, but you can change the name based on your own choice. But I have not changed my solution name. Solution name and project name both are same.

Additionally, there is a checkbox, if you have checked it, then the solution file (.Soln) and project files will be saved in the same folder. As shown in the following image.


After defining the required details, click on Next.

 Step 7 - Choose the Target Framework

Choose the target framework .NET 6.0 (Long-term support) which is the latest as shown in the following image.


After providing the required details, click the create button. It will create the ASP.NET Core MVC 6.0 web application as shown in step 8.

Step 8 - ASP.NET Core MVC 6.0 Folder Structure
The following is the default folder structure of the ASP.NET Core MVC 6.0 application.


Step 9 - Run the ASP.NET Core MVC 6.0 Application
You can build and run the application with default contents or let open the Index.cshtml file and put some contents there. Here I have some changes in index page.
Now press F5 on the keyboard or use the run option from Visual Studio to run the application in the browser. After running the application, it will show in the browser.

I hope, you have learned how to create the ASP.NET Core MVC 6.0 Web Application.

In this article, we explained how to create ASP.NET Core MVC 6.0 application. I hope this article is useful and easy to understand.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Swagger For .NET Core MVC Web API

clock February 14, 2022 07:26 by author Peter

Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification. Swagger UI is an alternative to Postman.

I used Swagger more than several times in my articles, but just as a minor tool used in different topics. When I tried to get info of Swagger, I had to search from these articles, which were not convinient. So, I rewrite these two articles, especially about Swagger for .NET MVC Web API or .NET Core MVC Web API.

If we created a new .NET Core 5.0 Web API project, the Swagger cient for Web API would be installed by default. In our current case, although we use .NET Core 5.0, the Web API is created in a MVC module, so we need to install Swagger manually. This way will work for the .NET Core version before 5.0.

This article is part of my another article: Consume Web API By MVC In .NET Core (1), Server And Framework, we got Swagger related part here. You can see details from there.
Step 1 - Create an ASP.NET Core MVC application

We use the version of Visual Studio 2019 16.8 and .NET 5.0 SDK to build the app.

    Start Visual Studio and select Create a new project.
    In the Create a new project dialog, select ASP.NET Core Web Application > Next.
    In the Configure your new project dialog, enter MVCCallWebAPI for Project name.
    Select Create.
    In the Create a new ASP.NET Core web application dialog, select,
     
        .NET Core and ASP.NET Core 5.0 in the dropdowns.
        ASP.NET Core Web App (Model-View-Controller).
        Create

Build and run the app, you will see the following image shows the app,


Step 2~3 - Scaffold API Controller with Action using Entity Framework

Please see the article, Consume Web API By MVC In .NET Core (1), Server And Framework,
B: Add Web API with Entity Framework Code First

    Step 1: Set up a new Database context
    Step 2: Work with a database using Entity Framework code first appoach.
    Step 3,:Scaffold API Controller with Action using Entity Framework

Step 4 - Add Swagger client for Web API

1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger

Step 2~3 - Scaffold API Controller with Action using Entity Framework

Please see the article, Consume Web API By MVC In .NET Core (1), Server And Framework,
B: Add Web API with Entity Framework Code First

    Step 1: Set up a new Database context
    Step 2: Work with a database using Entity Framework code first appoach.
    Step 3,:Scaffold API Controller with Action using Entity Framework

Step 4 - Add Swagger client for Web API

1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger


There are three main components to Swashbuckle (Swagger), we only need to install two of them: SwaggerGen and SwaggerUI, the Swagger would be included.

2.  Register Swagger Client in startup.cs file
Add the Swagger generator to the services collection in the Startup.ConfigureServices method,
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v2", new OpenApiInfo { Title = "MVCCallWebAPI", Version = "v2" });
    });
    ......
}


Enable the middleware for serving the generated JSON document and the Swagger UI, in the Startup.Configure method,
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v2/swagger.json", "MVCCallWebAPI");
    });
    ......
}

Now, we are almost ready to run the app.

Step 5 - Run and Test the app

Before we run the app, modify the header of the file: Views/Shared/_layout.cshtml Views again to add Swagger (line 11~13), shown below,
<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-controller="StoresMVC" asp-action="Index">MVC app</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Swagger" asp-action="Index">Web API</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>

Now, we run the app,


Click Web API, we got the Swagger Client screen,


 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Show Dynamic List Using View Bag In ASP.NET MVC?

clock February 2, 2022 08:15 by author Peter

In this blog, we will learn about how we can show the dynamic list using View Bag in ASP.net MVC.

Step 1 - Create a Model
First create the Model and define the public properties of Model.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AspNetMVCPractice.Models {
    public class Employee {
        public int Id {
            get;
            set;
        }
        public string Name {
            get;
            set;
        }
        public string Address {
            get;
            set;
        }
        public string Country {
            get;
            set;
        }
        public string City {
            get;
            set;
        }
        public Department Department {
            get;
            set;
        }
    }
}


Step 2 - Define the Action Method in Controller
public ActionResult Index() {
    return View();
}

Step 3 - Create the List and Pass the Model to that List
The third step is to create the list of Employees inside your Action Method.
public ActionResult Index() {
    List < Employee > list = new List < Employee > () {
        new Employee() {
                Id = 1,
                    Name = "Mudassar",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
            new Employee() {
                Id = 2,
                    Name = "Asad",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
            new Employee() {
                Id = 3,
                    Name = "Mubashir",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
    };
    ViewBag.model = list;
    return View();
}

Step 4 - Pass the List to View bag
Pass the data of list to view bag using model,
List < Employee > list = new List < Employee > () {
    new Employee() {
            Id = 1,
                Name = "Peter",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
        new Employee() {
            Id = 2,
                Name = "Jan",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
        new Employee() {
            Id = 3,
                Name = "Rudolph",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
};
ViewBag.model = list;


Step 5 - Show the Data on Front End
Given below code is to show the dynamic list of data using view bag in asp.net MVC.
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="wrapper">
  <div class="container">
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Id</th>
          <th scope="col">Name</th>
          <th scope="col">Address</th>
          <th scope="col">City</th>
          <th scope="col">Country</th>
        </tr>
      </thead>
      @foreach (var item in ViewBag.model)
       {
      <tbody>
        <tr>
          <th scope="row">@item.Id</th>
          <td>@item.Name</td>
          <td>@item.Address</td>
          <td>@item.City</td>
          <td>@item.Country</td>
        </tr>
      </tbody>             }
    </table>
  </div>
</div>



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Attribute Routing in ASP.Net MVC 5.0

clock January 28, 2022 06:27 by author Peter

Routing is a pattern matching process that monitors the requests and determines what to do with each request. In other words we can say Routing is a mechanism for mapping requests within our MVC application.

When a MVC application starts the first time, the Application_Start () event of global.asax is called. This event registers all routes in the route table using the RouteCollection.MapRoute method.

Example
    routes.MapRoute(  
        "Default", // Route name  
        "{controller}/{action}/{id}", // URL with parameters  
        new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  
    );


MVC 5 supports a new type of routing called “Attribute Routing”. As the name suggests, Attribute Routing enables us to define routing on top of the controller action method.

Enabling Attribute Routing
To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration.
    public class RouteConfig  
    {  
        public static void RegisterRoutes(RouteCollection routes)  
        {  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
            routes.MapMvcAttributeRoutes();  
        }  
    }


We can also add a customized route within the same method. In this way we can combine Attribute Routing and convention-based routing.
    public class RouteConfig  
    {  
        public static void RegisterRoutes(RouteCollection routes)  
        {  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
            routes.MapMvcAttributeRoutes();   
            routes.MapRoute(  
                   "Default", // Route name  
                    "{controller}/{action}/{id}", // URL with parameters  
                    new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  
               );  
        }  
    }


Attribute Routing Example
A route attribute is defined on top of an action method. The following is the example of a Route Attribute in which routing is defined where the action method is defined.

In the following example, I am defining the route attribute on top of the action method
    public class HomeController : Controller  
    {  
        //URL: /Mvctest  
        [Route(“Mvctest”)]  
        public ActionResult Index()  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
    }}   

Attribute Routing with Optional Parameter
We can also define an optional parameter in the URL pattern by defining a question mark (“?") to the route parameter. We can also define the default value by using parameter=value.
    public class HomeController : Controller  
    {  
      
      // Optional URI Parameter  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
      
        [Route(“Mvctest /{ customerName ?}”)]  
        public ActionResult OtherTest(string customerName)  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
      
       // Optional URI Parameter with default value  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
      
       [Route(“Mvctest /{ customerName =0036952}”)]  
       public ActionResult OtherTest(string customerName)  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Route Prefixes
We can also set a common prefix for the entire controller (all action methods within the controller) using the “RoutePrefix” attribute.

Example
    [RoutePrefix(“Mvctest”)]  
    public class HomeController : Controller  
    {  
        // URL: /Mvctest/  
        [Route]  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
      
      // Optional URI Parameter  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
        [Route(“{ customerName }”)]  
        public ActionResult OtherTest(string customerName)  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


When we use a tide (~) sign with the Route attribute, it will override the route prefix.

Example
    [RoutePrefix(“Mvctest”)]  
    public class HomeController : Controller  
    {  
        // URL: /NewMvctest/  
        [Route(“~/NewMVCTest”)]  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Defining Default Route using Route Attribute
We can also define a Route attribute on top of the controller, to capture the default action method as the parameter.

Example
    [RoutePrefix(“Mvctest”)]  
    [Route(“action=index”)]  
    public class HomeController : Controller  
    {  
        // URL: /Mvctest/  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }   
      
        // URL: /Mvctest/NewMethod  
        public ActionResult NewMethod()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }

Defining Route name
We can also define a name of the route to allow easy URI generation.

Example
    [Route(“Mvctest”,  Name = "myTestURL")]  
    public ActionResult Index()  
    {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
    }


We can generate URI using Url.RouteUrl method.
    <a href="@Url.RouteUrl("mainmenu")">Test URI</a>  

Defining Area
We can define the "Area" name from the controller that belongs to the using RouteArea attribute. If we define the “RouteArea” attribute on top of the controller, we can remove the AreaRegistration class from global.asax.
    [RouteArea(“Test”)]  
    [RoutePrefix(“Mvctest”)]  
    [Route(“action=index”)]  
      
    public class HomeController : Controller  
    {  
        // URL: /Test/Mvctest/  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Attribute Routing gives us more control over the URIs in our MVC web application. The earlier way of routing (convention-based routing) is fully supported by this version of MVC. We can also use both type of routing in the same project.

    Attribute Routing with Optional Parameter



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Read Data From Excel File And Insert Into Database In ASP.NET MVC

clock January 18, 2022 08:01 by author Peter

I will show you how to connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then insert it into the database table.

To begin with, we will create an ExcelToDatabase in Home Controller which returns a View. This method will return a View from where we have to upload the excel file. Now we will create another method ExcelToDatabase.  Now if we make a get request then ExcelToDatabase will be called and for post request, ExcelToDatabase will be called. The following is the code to read excel files.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace ExcelReadData
{
    public class HomeController : Controller
    {
        // GET: ClonePanel
        public ActionResult ExcelToDatabase()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ExcelToDatabase()
        {
            bool result = false;
            ViewBag.data = null;

            if (Request.Files["FileUpload1"].ContentLength > 0)
            {
                string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();
                string query = null;
                string connString = "";

                string[] validFileTypes = { ".xls", ".xlsx" };

                string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName);
                if (!Directory.Exists(path1))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Content/Uploads"));
                }
                if (validFileTypes.Contains(extension))
                {
                    if (System.IO.File.Exists(path1))
                    { System.IO.File.Delete(path1); }
                    Request.Files["FileUpload1"].SaveAs(path1);

                    //Connection String to Excel Workbook
                    if (extension.Trim() == ".xls")
                    {
                        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                        result = Service.ImportExceltoDatabase(path1, connString, userId);
                    }
                    else if (extension.Trim() == ".xlsx")
                    {
                        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                        result = Service.ImportExceltoDatabase(path1, connString,userId);
                    }
                }
                else
                {
                    ViewBag.Error = "Please Upload Files in .xls, .xlsx or .csv format";
                }
            }
            if (result)
            {
                ViewBag.data = "Data Import Successfully from excel to database.";
            }
            else
            {
                ViewBag.data = "there is some issue while importing the Data.";
            }
            return View();
        }
    }
}


Here I have created a class Service that contains 1 method ConvertXSLXtoDataTable. The following is the code for the service class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;

namespace ExcelReadData
{
    public class Service : IDisposable
    {
        #region **Private Variables**

        private TestDatabaseEntities _dbContext;

        #region **Constructor**

        public ImportExceltoDatabase()
        {
            _dbContext = new TestDatabaseEntities();
        }
        #endregion

        public bool ImportExceltoDatabase(string strFilePath, string connString)
        {
            bool result = false;
            OleDbConnection oledbConn = new OleDbConnection(connString);
            DataTable dt = new DataTable();
            try
            {
                oledbConn.Open();
                using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn))
                {
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    DataSet ds = new DataSet();
                    oleda.Fill(ds);

                    dt = ds.Tables[0];

                    if (dt.Rows.Count > 0)
                    {
                        table tblObj = new table();
                        foreach (DataRow row in dt.Rows)
                        {
                            tblObj.Name = row["Name"].ToString();
                            tblObj.Name = row["Address"].ToString();
                            tblObj.Salary = (int)row["Salary"];
                            tblObj.Age = (int)row["Age"];
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                result = false;
            }
            finally
            {
                oledbConn.Close();
            }
            return result;
        }
    }
}


Now we have to create a view that contains file upload control and a button. When a request for ExcelToDatabase of Home Controller is made, it will show file upload control with button control. When the user selects a file and presses the button it will make a post request to Home Controller and the ExcelToDatabase method will be called. The following is the Razor View for both requests.
@using (Html.BeginForm("ImportExcel", "ExcelToDB", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table>
        <tr><td>Excel file</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr>
        <tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr>
        <tr><td></td><td><lable>@(viewbag.data)</lable></td></tr>
    </table>
}



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Removing or Customizing View Engines in MVC

clock January 14, 2022 07:48 by author Peter

In this article, you will learn how to remove or customize View Engines not being used by an application.
If you are not using any view engine like ASPX View Engine, it is better to remove it to improve the performance, it is one of the many MVC performance tuning tips.
 
You might be wondering how it will improve the performance. Let's prove it by creating a new action method in a Home Controller, don't add a view for this action method now.
    public ActionResult Foo()  
    {  
         return View();  
    }   

Now, run the application and try navigating to "http://localhost:1212/Home/Foo". Here is what I received:

In the image above you can see how the MVC runtime is looking for an ASPX View Engine first and then the other view engines, which is still a default behavior.

You can control it from the Global.asax file by taking advantage of ViewEngines.Engines.Clear().

    protected void Application_Start()  
    {  
           ViewEngines.Engines.Clear();  
           ViewEngines.Engines.Add(new RazorViewEngine());  
           AreaRegistration.RegisterAllAreas();  
           WebApiConfig.Register(GlobalConfiguration.Configuration);  
           FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
           RouteConfig.RegisterRoutes(RouteTable.Routes);  
           BundleConfig.RegisterBundles(BundleTable.Bundles);  
           AuthConfig.RegisterAuth();  
     }


I highlighted the newly added code above. Now, run the application; you will see the following:


You will see that the MVC runtime successfully removed the ASPX View Engine but it is still looking for VBHTML Views.

You can also control it by customizing Razor View Engine to use only C# languages, by making some changes here:
    ViewEngines.Engines.Add(new RazorViewEngine());  

I highlighted the portion of code. This is actually calling the RazorViewEngine. RazorViewEngine() method internally that has support for both languages (C# and VB) by default. So, we need to override the default functionality by adding a class by the name "CustomRazorViewEngine" that inherits RazorViewEngine. The best place to add this class file is in the App_Start folder.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    namespace MvcApplication1.App_Start  
    {  
        public class CustomRazorViewEngine : RazorViewEngine  
        {  
            public CustomRazorViewEngine()  
            {  
                base.AreaViewLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.AreaMasterLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.AreaPartialViewLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.ViewLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
                base.PartialViewLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
                base.MasterLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
            }  
        }  
    }

Remember to use the System.Web.Mvc namespace. Now, in the Global.asax file add the following code:
    protected void Application_Start()  
    {  
        ViewEngines.Engines.Clear();  
        //ViewEngines.Engines.Add(new RazorViewEngine());  
        ViewEngines.Engines.Add(new CustomRazorViewEngine());  
        AreaRegistration.RegisterAllAreas();  
        WebApiConfig.Register(GlobalConfiguration.Configuration);  
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
        RouteConfig.RegisterRoutes(RouteTable.Routes);  
        BundleConfig.RegisterBundles(BundleTable.Bundles);  
        AuthConfig.RegisterAuth();  
    }


Remember to use the MvcApplication1.App_Start namespace to bring the class file created above into the Global.asax scope. Now, run the application, you will see the following output:


 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in