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 :: Pass Data Across Views In .NET MVC

clock January 10, 2023 06:17 by author Peter

In previous articles, we discussed both View Variables in ASP.NET MVC and View Variables in ASP.NET Core MVC, respectively.  Although each has some distinctive points, both share a lot of common features. In this article, we will discuss something new: pass data across views. We will also summarize some common or important shared features for various vew variables.


A: Brief Summary of ViewData
We will start our discussion from ViewData, but most or all features are the same for other MVC View Variables. The ASP.NET Core also has the same features. So, we will discuss ViewData in the most, and have the last part to see the extension to other View variables.

A - 1: MVC Data Passing Techniques
This is a different approach to summarize the MVC Data Passing Techniques from Data Passing Techniques in ASP.NET Core (dotnettricks.com). We will not repeat the conclusion here, but we can go to the page to learn the different approaches or understanding.

B: Type of ViewData
We have discussed ViewData, ViewBag, TempData, Session type features. They are all the Type of Dictionary:

Where the difference between ViewBag and ViewData:


Besides ViewBag, all other View Variables need to be cast before using. We define a ViewData named "book": as type BookModel with data such as Id = 1:


When we retrieve data, we have to cast the data back to the data type. Otherwise, we will get an error message:


After casting:

C: Pass Data into _Layout.cshtml Page by ViewData
The _layout.cshtml is a shared page by other specific views. It belongs to no Controller or Action, or we can say it belongs to every Controller or Action when the related view is using _layout.cshtml. Therefore, we can pass data into Layout either from the Controller or Action view, which uses the _layout.cshtml, such as, if we have a Contact Us Action:

Or, we can define the ViewData from the Contact Us View:

Both ways will pass the data into Layout page:

Notes
1, We usually introduce the Layout into View by the code in the View as below:

2, in some cases, if we want to make the Layout page(s) dynamic, we can assign the layout to the view through Controller/Action:

3, A related important shared concept for MVC, _Viewstat.cshtml

D: Pass Data into _Layout.cshtml Page by Other View Variables
The same is true for other MVC View Variables, such as ViewBag, TempData, and absolutely Session variable:


Pass TempData to Layout:

Pass ViewData to Layout:

Pass ViewBag to Layout:

This article discussed using ASP.NET MVC ViewData to pass data into Layout View through either Controller or View.  The features are available or the same as other View Variables in ASP.NET MVC, and the same is true for ASP.NET Core MVC.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: CRUD Operation With Dapper Using ASP.NET Core 6 MVC

clock December 6, 2022 08:03 by author Peter

In this article will learn CURD (Create, Update, Read and Delete) operation which is common for most web applications. Here will understand SQL Database, Dapper Micro-ORM (Object Relation Mapper) along with repository pattern using ASP.NET Core 6 MVC.


What is Dapper?
Dapper is a micro ORM or it is a simple object mapper framework that helps to map the native query output to a domain class.
Creating a New Project in Visual Studio 2022

Start Visual Studio software and select Create a new project.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.

In the Configure your new project dialog, enter CURDWithDapperCore6MVC_Demo for Project name. It's important to name the project CURDWithDapperCore6MVC_Demo. The capitalization needs to match each namespace when code is copied. Select Next.

In the Additional information dialog, select .NET 6.0 (Long-term support). Select Create

The Visual Studio project 2022 will now generate the structure for the selected application. In this example, we are using ASP.Net MVC so we can create a controller to write the code, or so we can use the existing controller. There you can enter the code and build/run the application.
Install the Dapper, Microsoft.Data.SqlClient Library through NuGet Package Manager

The Visual Studio software provides the NuGet Package manager option to install the package directly to the solution.

In Visual Studio Select Tools > NuGet Package Manager > Manage NuGet Packages for the solution. The below screenshot shows how to open the NuGet Package Manager.

Search for the specific package Dapper, Microsoft.Data.SqlClient using the search box on the upper left. Select a package from the list to display its information, enable the Install button and a version-selection drop-down, as shown in the below screenshot. The NuGet package will be installed for your project and reference will be added, as seen in the screenshot below.

In the above image, we can see the list of the related search items. We need to select the required option to install the package to the solution.

Add Connection String
In solution explorer select a file appsettings.json double click on this file to open "Add" connection string as shown below.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=Companies-DB;Integrated Security=True;Pooling=False;Encrypt=false"
  }
}


Add Models class
Right-click the Models folder > Add > Class. Name the file Company.cs
using System.ComponentModel.DataAnnotations;

namespace CURDWithDapperCore6MVC_Demo.Models
{
    public class Company
    {
        public int Id { get; set; }
        [Display(Name ="Company Name")]
        public string CompanyName { get; set; }

        [Display(Name = "Company Address")]
        public string CompanyAddress { get; set; }

        public string Country { get; set; }

        [Display(Name = "Glassdoor Rating")]
        public int GlassdoorRating { get; set; }
    }
}


Add DBContext Folder and DapperContext Class
Right click on Project in Solution Explorer>Add New>New Folder. Rename this folder to DBContext. Now right click on DBContext folder > Add> New Item> C# class name this class DapperContext.

using Microsoft.Data.SqlClient;
using System.Data;

namespace CURDWithDapperCore6MVC_Demo.DBContext
{
    public class DapperContext
    {
        private readonly IConfiguration _configuration;
        private readonly string _connectionString;
        public DapperContext(IConfiguration configuration)
        {
            _configuration = configuration;
            _connectionString = _configuration.GetConnectionString("DefaultConnection");
        }
        public IDbConnection CreateConnection() => new SqlConnection(_connectionString);
    }
}


Add Repositories Folder and ICompanyRepository Interface

Right click on Project in Solution Explorer>Add New>New Folder. Rename this folder to Repositories. Now right click on DBContext folder > Add> New Item>C# Interface and name this interface ICompanyRepository.
using CURDWithDapperCore6MVC_Demo.Models;

namespace CURDWithDapperCore6MVC_Demo.Repositories
{
    public interface ICompanyRepository
    {
        Task<IEnumerable<Company>> GetCompanies();
        Task<Company> GetCompany(int? id);
        Task CreateCompany(Company company);
        Task UpdateCompany(int id, Company company);
        Task DeleteCompany(int id);
    }
}


Add Company Repository class to Implement Interface

Right click on Repositories Add> New Item>C# class and name this class to CompanyRepository.
using CURDWithDapperCore6MVC_Demo.DBContext;
using CURDWithDapperCore6MVC_Demo.Models;
using Dapper;
using System.Data;

namespace CURDWithDapperCore6MVC_Demo.Repositories
{
    public class CompanyRepository : ICompanyRepository
    {
        private readonly DapperContext context;

        public CompanyRepository(DapperContext context)
        {
            this.context = context;
        }

        public async Task<IEnumerable<Company>> GetCompanies()
        {
            var query = "SELECT * FROM Companies";

            using (var connection = context.CreateConnection())
            {
                var companies = await connection.QueryAsync<Company>(query);
                return companies.ToList();
            }
        }

        public async Task<Company> GetCompany(int? id)
        {
            var query = "SELECT * FROM Companies WHERE Id = @Id";

            using (var connection = context.CreateConnection())
            {
                var company = await connection.QuerySingleOrDefaultAsync<Company>(query, new { id });
                return company;
            }
        }

        public async Task CreateCompany(Company company)
        {
            var query = "INSERT INTO Companies (CompanyName, CompanyAddress, Country,GlassdoorRating) VALUES (@CompanyName, @CompanyAddress, @Country, @GlassdoorRating)";

            var parameters = new DynamicParameters();
            parameters.Add("Name", company.CompanyName, DbType.String);
            parameters.Add("Address", company.CompanyAddress, DbType.String);
            parameters.Add("Country", company.Country, DbType.String);
            parameters.Add("Country", company.GlassdoorRating, DbType.Int32);

            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, parameters);
            }
        }

        public async Task UpdateCompany(int id, Company company)
        {
            var query = "INSERT INTO Companies (CompanyName, CompanyAddress, Country,GlassdoorRating) VALUES (@CompanyName, @CompanyAddress, @Country, @GlassdoorRating WHERE Id = @Id)";
            var parameters = new DynamicParameters();
            parameters.Add("Name", company.CompanyName, DbType.String);
            parameters.Add("Address", company.CompanyAddress, DbType.String);
            parameters.Add("Country", company.Country, DbType.String);
            parameters.Add("Country", company.GlassdoorRating, DbType.Int32);
            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, parameters);
            }
        }
        public async Task DeleteCompany(int id)
        {

            var query = "DELETE FROM Companies WHERE Id = @Id";
            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, new { id });
            }
        }
    }
}

Add a controller
In Solution Explorer, right-click Controllers > Add > Controller.
In the Add New Scaffolded Item dialog box, select MVC Controller – MVC Controller with read/write actions > Add.
In the Add New Item - Companies dialog, enter CompaniesController.cs and select Add.
Replace the contents of Controllers/ CompaniesController.cs with the following code:

Add a view

Right-click on the Action in CompaniesController, and then Add View.
In the Add New Scaffolded Item dialog:
    Select Razor View Select Add
    View Name: Index
    Template: List
    Model Class: Company
    Select Add

Replace the contents of the Views/Companies/Index.cshtml Razor view file with the following:
@model IEnumerable<CURDWithDapperCore6MVC_Demo.Models.Company>

@{
    ViewData["Title"] = "Index";
}

<h2 class="text-capilization text-center">List of Companies</h2>

<p>
    <a asp-action="Create" class="btn btn-primary"> <i class="fa-solid fa-circle-plus"></i> Add New</a>
</p>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Id)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CompanyName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CompanyAddress)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Country)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GlassdoorRating)
            </th>
            <th>Action(s)</th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyAddress)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Country)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.GlassdoorRating)
            </td>
            <td>
                 <a href="@Url.Action("Details",new { id=item.Id})" class="btn btn-sm btn-primary"><i class="fa-solid fa-eye"></i></a>
                 <a href="@Url.Action("Edit",new { id=item.Id})" class="btn btn-sm btn-info"><i class="fa-solid fa-pen-to-square"></i></a>
                 <a href="@Url.Action("Delete",new { id=item.Id})" class="btn btn-sm btn-danger"><i class="fa-solid fa-trash"></i></a>
            </td>
        </tr>
}
    </tbody>
</table>

Note: Similarly Add all action view like Details, Create, Edit and Delete
Now its time to build and run your application Ctrl+F5

 

The above article has taught us. How we can use dapper with repository pattern. Dapper is Micro ORM whereas Entity Framework is ORM. Dapper is faster than entity framework. Hope you enjoyed the article. Happy Coding.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Working With Areas In MVC

clock November 30, 2022 07:27 by author Peter

The primary purpose of areas in MVC is to separate and manage Model, View, Controller, Themes and routing registration file into separate sections. In other words, areas serve as a technique for dividing and managing a large Application into well managed smaller modules with the separate M-V-C in each module.


Why to use areas in MVC Application?
If you are building a CRM Application for a small Educational Consultancy with multiple business units such as Registration on Arrival, Information Gathering by Receptionist, Updates by Consular, Documentation Management, Interview Preparation, Billing, and Report Generation by different departments etc. Each of these units have their own logical components views, controllers and models. In this scenario, you can use ASP.NET MVC areas to physically partition the business components in the same project.

It is also possible that we can have large projects that uses MVC, then we need to split the Application into smaller units called areas that isolates the larger MVC Application into smaller functional groupings. A MVC Application can contain several MVC structures (areas).

Areas are the small functional units with its own set of Model, View and Controller

    MVC Application can have any number of areas.
    Each area has its own controllers, models and views.
    Areas are put under separate folders called areas.

Today, we will be creating a new ASP.NET MVC Application and define a new area inside the project.

Creating new MVC Application


Step 1
Open Visual Studio.

Step 2
Create an ASP.NET Web Application with MVC template, as shown below.

Step 3
In Solution Explorer, right-click on the project and click Add. Select areas to add an area.

Step 4
Enter the name for the area, such as "Consular" or “SuperAdmin”.

Adding Controller for Area
Now, let’s add a controller in Area.

Step 1
Right-click on the Controller in your article area to add a controller.

Step 2
Select "MVC 5 Empty Controller.


Step 3
Provide controller name as "ManageInterviewController”. Now, your Area folder should look, as shown below.

Adding Views for Area
We have successfully added a controller for our area. Now, let’s add a view for the area.

Step 1
Right-click on the "Index" method of ManageInterviewConsular Controller and click on Add View.

Step 2
Enter the view name and select Layout page.

Step 3
Generate some content in the View of Index method, as shown below.


Index g (table table-hover table-bordered table-responsive" >Time< /tr>Kathmandu< /tr> " "picture_x0020_6"="">
 
Area Registration
Step 1
Open the "Global.asax" file.

Step 2
Add the code given below in your Application_Start() method.

AreaRegistration.RegisterAllAreas();


Till here, we have successfully added an area. Inside Area is the one, where we have added aController and a View for Index method.
Now, let’s add a link in Navbar of an Application to navigate to the view, which we created just now.

Step 1
Open the project view Layout file.

Step 2
Modify the <ul> </ul> in the layout file, as shown in the code given below.

Step 3
Debug the Application and open List Interview link, as shown below.

Let’s notice the URL
As highlighted, to invoke the controller of the area, we need to use

Baseurl/Areaname/Controller/{actionname}




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Single Sign-On Using ASP.NET MVC And ASP.NET Core

clock November 21, 2022 07:28 by author Peter

What is single sign-on (SSO)?
Users must authenticate themselves to access pages protected by a web application, and if a user accesses multiple web applications, they must be authenticated. You must log in to each application separately.

Single Sign-on using ASP.NET MVC and ASP.NET CORE
Interested in using single sign-on (SSO) for your ASP.NET MVC app? You're in the right place. There are many reasons to use SSO for custom apps owned by the same organization.

    Improved user experience.
    Reduce development time.
    Improved security.

These are all good reasons.

Another thing I like about SSO is that it allows me to update large code bases in small increments instead of all at once.

As? Suppose you want to migrate an app written in ASP.NET MVC 5 to ASP.NET Core MVC. Instead of rewriting everything at once, you can migrate one service at a time. By implementing SSO between two apps, you can effectively connect the two apps as if they were one app.

This tutorial simulates such a scenario by implementing his SSO in an MVC 5 app and a .NET Core app. Along the way, you'll also learn about the differences in how the two platforms implement authentication.

Find the ASP.NET MVC 5 App

Access an existing MVC 5 app from GitHub instead of building a project from scratch. Clone or download this project (https://github.com/oktadev/aspnet-mvc-crud-example) and open the solution in Visual Studio.

Web.config file has some app settings used by programmers to configure authentication with the Open ID Connect server provided by Okta:
<add key="okta:ClientId" value="{yourClientId}" />
<add key="okta:ClientSecret" value="{yourClientSecret}" />
<add key="okta:OktaDomain" value="https://{yourOktaDomain}" />


For this tutorial, you'll need to switch these values ​​to your own Okta instance. Sign in to your Okta domain if you already have an account, or sign up for a forever free developer account if you don't already have one.

After signing in to Okta, register your client application.

    Click Applications on the top menu.
    Click Add Application.
    Select Web and click Next.
    Enter SSO MVC 5 for Name.
    For the Grant type allowed check the Implicit (Hybrid) checkbox
    And last click on DONE

The application has been created, but we still need to add something. Select Edit and add http://localhost:8080/Account/PostLogout to the logout redirect URI list and click Save.

On the next screen, you will see a summary of your settings. Under the General Settings section, you will see the Client Credentials section. Update the SSO settings in Web.config with your client ID and client secret. Next, go to the main page of your Okta dashboard, copy the organization URL shown in the top left corner, and paste it into Okta.

OktaDomain app settings in Web.config.

At this point, you should be able to run your app and sign in and out using OpenID Connect. If you're interested, take a look at Startup.cs to see how the authentication middleware is configured.

Find the ASP.NET Core App

Now that you're using Okta to log into your MVC 5 app, adding SSO to your second app is trivial.

First, download or clone this .NET Core app from GitHub.(https://github.com/oktadeveloper/okta-aspnetcore22-crud-example) If opening in Visual Studio, change the debug target from IIS Express to LiveMusicFinder.

This will run your app through the Kestrel web server on port 5001 (for https).

Go back to your Okta admin panel and register this application.
    click on Applications at top of the menu
    Then click on Add Application
    And select Web and click Next
    Enter SSO Core MVC for the Name
    Replace Base URIs with https://localhost:5001/
    Replace Login redirect URIs with https://localhost:5001/authorization-code/callback
    Click Done

Once complete, you'll be taken to the General Settings tab of the app. In this tab, click the Edit button and add an entry to the Signout Redirect URI as https://localhost:5001/signout/callback.

Then click Save.

Copy the Client ID and Client Secret from the Client Credentials section of the next page and update your application's appsettings.json file.
"Okta": {
  "ClientId": "{yourClientId}",
  "ClientSecret": "{yourClientSecret}",
  "OktaDomain": "https://{yourOktaDomain}",
  "PostLogoutRedirectUri": "https://localhost:5001/"
},


While editing the settings, update the OktaDomain settings to match what you entered in your MVC 5 app's Web.config. Also change the PostLogoutRedirectUri to https//local host:5001/.

That's really it. When you sign in to either app, click the Sign In link in the other app to automatically sign you in without prompting for your password.

(If you're inexplicably testing this using Internet Explorer and Visual Studio's auto-launch feature, make sure you're opening her second app in a tab in her window in the first browser. . Each browser window is isolated from the others due to Visual Studio's habit of launching IE.)
How single sign-on works in ASP.NET MVC 5 and ASP.NET Core

We've seen how easy it is to enable SSO in two ASP.NET apps, but what's really going on behind the scenes to make it work?

Suppose you first navigate to App 1 and click Sign In. App 1 redirects to Okta IdP (Identity Provider) where it signs in. When you log in, a cookie from Okta's domain is set in your browser. This cookie keeps you logged into Okta. Okta then returns to App 1 with the token it uses to complete the sign-in process. At this point, her cookie is also set on the App 1 domain. Here's a diagram to explain the states:


Then open app 2 in another tab in the same browser. Click Sign In and you will be redirected back to the Okta IdP. However, this time we still have a valid cookie, so we are already logged into the IdP. So instead of showing a login screen, Okta simply redirects to App 2 with the token needed to complete the local login process. A cookie is set on the domain of app 2 and you can log in from anywhere.

Note that Single sign-out_ is not supported by Okta as of this writing. When you log out of App 1, the cookies in App 1 are deleted and a quick call is made to the Okta IdP, which deletes the cookies. However, the App 2 cookie remains and you remain signed in to App 2 until you click Sign Out or the cookie expires. The default expiration is 30 days.
Explain ASP.NET OpenID Connect Flow

As you may have noticed, when I set up the configuration for my MVC 5 app I had to check the box to enable the implicit (hybrid) grant type, but not for .NET Core apps was.

When the OpenID Connect middleware was written for his MVC 5 years ago (long time ago in the software world), the OpenID Connect hybrid flow was implemented. This flow requires the IdP to pass an authorization code and ID token to the MVC 5 app submission. When redirecting the user to your app.

When the OpenID Connect middleware was written for .NET Core, it implemented a more secure authorization code flow. In this case the IdP should only return an authorization code and the middleware should get the ID token via a backchannel request to his IdP. This means that the ID token is not exposed to browsers. Note that if you pass sensitive information in an ID token, in MVC 5 this token will be returned to your app via the browser. This is not a problem when enabling SSO for him for .NET Core apps.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Generating An Excel File Through A List Of Objects In ASP.NET MVC

clock October 10, 2022 09:21 by author Peter

Today I will show you how to generate an excel file from a list of objects in C#. To do this, several plugins allow you to do this work in a global way. In this work, I will try to create a very simple and generic method to generate an excel file from a list of objects whatever their nature.


Step 1
Create a new ASP.NET MVC project.

Give a name to this project. for example "ExcelGeneratingApp".

Choose the MVC type.

Step 2

Create a class "ExcelLib.cs" in the models folder of the application.

Step 3

Add "ClosedXML" library from Nuget Package Manager.

Add class named "Employee.cs" for example.
using System.ComponentModel;
namespace ExcelGeneratingApp.Models
{
public class Employee
{
[DisplayName("Identity number")]
public int ID { get; set; }
[DisplayName("Full name")]
public string Name { get; set; }
[DisplayName("Age")]
public int Age { get; set; }
[DisplayName("Salary")]
public float Salary { get; set; }
[DisplayName("Department name")]
public string Department { get; set; }

}
}


​Add an "addHeader" method to "ExcelLib.cs" class. This method allows to add and style header of the table in excel file.
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace ExcelGeneratingApp.Models
{
public class ExcelLib
{
// Default Constructor.
public ExcelLib() { }
// Method for adding Header and Title of the table containing List of object values.
public IXLWorksheet addHeader(XLWorkbook wb, List<Object> objs, string title,  string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Sheet initialisation.
var ws = wb.Worksheets.Add("nomDeLaListe").SetTabColor(XLColor.UaBlue);
// font choice.
ws.Style.Font.FontName = fontFamily;
ws.Style.Font.SetFontSize(13);
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Style.Alignment.WrapText = true;
Object obj = objs.FirstOrDefault();
// Add the model fields to the header of the excel file.
int totalOfFields = obj.GetType().GetProperties().Length; // number of fields in the object.
int numberOfFields = 0;
// Adding the title of table in excel file.
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Value = title;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Style.Fill.BackgroundColor = XLColor.FromHtml(color); ;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.Bold = true;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontColor = XLColor.WhiteSmoke;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontSize = 18;
//Looping all propeties of the object.
foreach (var prop in obj.GetType().GetProperties())
{
        var displayNameAttribute = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false);
        string displayName = prop.Name;
        if (displayNameAttribute.Count() != 0)
        {
            displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
        }
        numberOfFields++;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Value = displayName;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        ws.Column(totalOfFields - numberOfFields + 4).Width = 30;
        ws.Column(totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
}
ws.Range(ws.Cell(5, 4), ws.Cell(5, totalOfFields + 3)).SetAutoFilter();
return ws;
}
}
}


Then add "addBody" method to the "ExcelLib.cs" class.
This method allows to add the list of objects "objs" content to the table in excel file.
It merges the cells of the first column containing the same values.
public IXLWorksheet addBody(IXLWorksheet ws, List<Object> objs)
{
int numberOfFields = 0;
int numberOfRecords = 0;
Object obj = objs.FirstOrDefault();
int totalOfFields = obj.GetType().GetProperties().Length;
string previousValue = "";
int indexOfPreviousValue = 0;

foreach (var item in objs.ToList())
{
  numberOfFields = 0;
  Type myType = item.GetType();
  IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

  foreach (PropertyInfo prop in props)
  {
      object propValue = prop.GetValue(item, null);

      numberOfFields++;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Value = propValue;

      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Font.Bold = true;

      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;

      if (numberOfFields == 1 && numberOfRecords == 0)
      {
          previousValue = propValue.ToString();
      }
      else
      {
          if (numberOfFields == 1)
          {
              if (previousValue == propValue.ToString())
              {
                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Value = propValue.ToString();

                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                  indexOfPreviousValue++;
              }
              else
              {
                  previousValue = propValue.ToString();
                  indexOfPreviousValue = 0;
              }
          }

      }


  }
  numberOfRecords++;
}

return ws;
}


Then add a "Generate" method for generating the excel file.
public void Generate(List<Object> objs, string title, string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Workbook creation.
using (XLWorkbook wb = new XLWorkbook())
{
        var ws = addHeader(wb, objs, title);
            ws = addBody(ws, objs);
            wb.SaveAs("C://TestExcelGen.xlsx");
}
}

Step 4
To test this method, we will add some code to the Home controller.
public ActionResult Index()
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { ID = 100 ,Name="PETER", Age=32,Salary=12000,Department="INFO"}) ;
employees.Add(new Employee() { ID = 200 ,Name="SCOTT", Age=24,Salary=10000,Department="CIVIL"}) ;
employees.Add(new Employee() { ID = 300 ,Name="ADAM", Age=20,Salary=11000,Department="INDUS"}) ;
employees.Add(new Employee() { ID = 400 ,Name="ETHAN", Age=21,Salary=9000,Department="INFO"}) ;
ExcelLib excel = new ExcelLib();

excel.Generate(employees.Cast<object>().ToList(), "List of employees");

return View();
}

The full ExcelLib.cs content:
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;

namespace ExcelGeneratingApp.Models
{
public class ExcelLib
{
// Default Constructor.
public ExcelLib() { }
// Method for adding Header and Title of the table containing List of object values.
public IXLWorksheet addHeader(XLWorkbook wb, List<Object> objs, string title,  string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Sheet initialisation.
var ws = wb.Worksheets.Add("nomDeLaListe").SetTabColor(XLColor.UaBlue);
// font choice.
ws.Style.Font.FontName = fontFamily;
ws.Style.Font.SetFontSize(13);
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Style.Alignment.WrapText = true;
Object obj = objs.FirstOrDefault();
// Add the model fields to the header of the excel file.
int totalOfFields = obj.GetType().GetProperties().Length; // number of fields in the object.
int numberOfFields = 0;
// Adding the title of table in excel file.
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Value = title;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Style.Fill.BackgroundColor = XLColor.FromHtml(color); ;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.Bold = true;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontColor = XLColor.WhiteSmoke;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontSize = 18;
//Looping all propeties of the object.
foreach (var prop in obj.GetType().GetProperties())
{
        var displayNameAttribute = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false);
        string displayName = prop.Name;
        if (displayNameAttribute.Count() != 0)
        {
            displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
        }
        numberOfFields++;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Value = displayName;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        ws.Column(totalOfFields - numberOfFields + 4).Width = 30;
        ws.Column(totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
}
ws.Range(ws.Cell(5, 4), ws.Cell(5, totalOfFields + 3)).SetAutoFilter();
return ws;
}
public IXLWorksheet addBody(IXLWorksheet ws, List<Object> objs)
{
int numberOfFields = 0;
int numberOfRecords = 0;
Object obj = objs.FirstOrDefault();
int totalOfFields = obj.GetType().GetProperties().Length;
string previousValue = "";
int indexOfPreviousValue = 0;

foreach (var item in objs.ToList())
{
    numberOfFields = 0;
    Type myType = item.GetType();
    IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

    foreach (PropertyInfo prop in props)
    {
        object propValue = prop.GetValue(item, null);
        numberOfFields++;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Value = propValue;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;

        if (numberOfFields == 1 && numberOfRecords == 0)
        {
            previousValue = propValue.ToString();
        }
        else
        {
            if (numberOfFields == 1)
            {
                if (previousValue == propValue.ToString())
                {
                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Value = propValue.ToString();

                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    indexOfPreviousValue++;
                }
                else
                {
                    previousValue = propValue.ToString();
                    indexOfPreviousValue = 0;
                }
            }
        }
    }
    numberOfRecords++;
}
return ws;
}
public void Generate(List<Object> objs, string title, string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Workbook creation.
using (XLWorkbook wb = new XLWorkbook())
{
        var ws = addHeader(wb, objs, title);
            ws = addBody(ws, objs);
            wb.SaveAs("C://TestExcelGen.xlsx");
}
}
}
}

NB: You can download all project source code from my github page.

Conclusion
I think the procedure is very clear with snapshots. If you have found any mistake in concept, please do comment. Your comments will make me perfect in the future.
Thanks for reading.

 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Pass Data Across Views In .NET MVC

clock September 30, 2022 09:46 by author Peter

In this article, we will discuss something new: pass data across views. We will also summarize some common or important shared features for various vew variables.

Brief Summary of ViewData
We will start our discussion from ViewData, but most or all features are the same for other MVC View Variables. The ASP.NET Core also has the same features. So, we will discuss ViewData in the most, and have the last part to see the extension to other View variables.


Type of ViewData
We have discussed ViewData, ViewBag, TempData, Session type features. They are all the Type of Dictionary:

Where the difference between ViewBag and ViewData:

Besides ViewBag, all other View Variables need to be cast before using. We define a ViewData named "book": as type BookModel with data such as Id = 1:


When we retrieve data, we have to cast the data back to the data type. Otherwise, we will get an error message:

After casting:

Pass Data into _Layout.cshtml Page by ViewData
The _layout.cshtml is a shared page by other specific views. It belongs to no Controller or Action, or we can say it belongs to every Controller or Action when the related view is using _layout.cshtml. Therefore, we can pass data into Layout either from the Controller or Action view, that uses the _layout.cshtml, such as, if we have a Contact Us Action:

Or, we can define the ViewData from the Contact Us View:

Both ways will pass the data into Layout page:

Notes
1, We usually introduce the Layout into View by the code in the View as below:

2, in some cases, if we want to make the Layout page(s) dynamic, we can assign the layout to the view through Controller/Action:

3, A related important shared concept for MVC, _Viewstat.cshtml


Pass Data into _Layout.cshtml Page by Other View Variables
The same is true for other MVC View Variables, such as ViewBag, TempData, and absolutely Session variable:


Pass TempData to Layout:

Pass ViewData to Layout:

Pass ViewBag to Layout:

This article discussed using ASP.NET MVC ViewData to pass data into Layout View through either Controller or View.  The features are available or the same as other View Variables in ASP.NET MVC, and the same is true for ASP.NET Core MVC.



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Data Sharing Techniques In MVC

clock August 29, 2022 08:55 by author Peter

1) View Data

ViewData is a built-in object of the "ViewDataDictionary" class.
ViewData stores the data in key-value pairs

Example
public IActionResult Index() {
    ViewData["Name"] = "MVC";
    return View();
}


Output

2) View Bag
ViewBag is also used for sending Data from the controller to View.
ViewBag is developed based on Dynamic Typing.
No need to perform Type Casting
Use key as property

Example
public IActionResult ViewBagIndex() {
    ViewBag.Name = "MVC";
    return View();
}


Output


3) Temp Data
TempData is used to transfer the aata from one Action to Another Action at the time of redirection
TempData is an object of the "TempDataDictionary" class

Example
public ActionResult TempDataIndex() {
    TempData["Name"] = "MVC";
    return View();
}

Output

Please do leave a comment if you find it useful.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Generate QR Code In ASP.NET MVC Core 6?

clock July 11, 2022 07:44 by author Peter

In this article, we will learn how to generate QR codes in ASP.NET MVC Core 6 by simply entering Text, numbers, and a combination of both in the textbox and clicking on generate QR code button. I found a very useful library for generating QR codes which are IronBarcode. Download code and play with it.


You can install it through the NuGet package. It supports .Net Core, Standard & Framework. It has cross-platform support.

To use this library we will create a demo project in Visual Studio. I am creating ASP.NET Core Web App (Model-View-Controller). I am going to use the Visual Studio 2022 version.
Creating a New Project in Visual Studio

Start Visual Studio software and select Create a new project.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View-Controller) > Next.


In the Configure your new project dialog, enter GenerateQRCode_Demo for the Project name. It's important to name the project GenerateQRCode_Demo. Capitalization needs to match each namespace when code is copied. Select Next.


In the Additional Information dialog, select .NET 6.0 (Long-term support). Select Create.


The Visual Studio project 2022 will now generate the structure for the selected application, and in this example, we are using ASP.Net MVC So we can create a controller to write the code or we can use the existing controller where you can enter the code and build/run the application.

Next, we can add the library to test the code.

How to Install the Barcode Library through NuGet Package Manager?

The Visual Studio software provides the Nuget Package manager option to install the package directly to the solution.

In Visual Studio Select Tools > NuGet Package Manager > Manage NuGet Packages for the solution. The below screenshot shows how to open the Nuget Package Manager.


Search for the specific package IronBarcode using the search box on the upper left. Select a package from the list to display its information, enabling the Install button and a version-selection drop-down. As shown below screenshot. The NuGet package will be installed for your project and reference will be added. As in the screenshot below.

In the above image, we can see the list of the related search items. We need to select the required option to install the package to the solution.
Using the Visual Studio Command-Line

In Visual Studio, go to Tools-> Nuget Package Manager -> Package Manager Console

Enter the following line in the package manager console tab:

Install-Package IronBarCode

Now the package will download/install to the current project and be ready to use.

Add a class in the Models folder and write or copy-paste the below code.
using System.ComponentModel.DataAnnotations;
namespace GenerateQRCode_Demo.Models {
    public class GenerateQRCodeModel {
        [Display(Name = "Enter QR Code Text")]
        public string QRCodeText {
            get;
            set;
        }
    }
}


We will use exiting HomeController to write the code.
using GenerateQRCode_Demo.Models;
using IronBarCode;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Drawing;
namespace GenerateQRCode_Demo.Controllers {
    public class HomeController: Controller {
        private readonly IWebHostEnvironment _environment;
        public HomeController(IWebHostEnvironment environment) {
            _environment = environment;
        }
        public IActionResult CreateQRCode() {
                return View();
            }
            [HttpPost]
        public IActionResult CreateQRCode(GenerateQRCodeModel generateQRCode) {
            try {
                GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText, 200);
                barcode.AddBarcodeValueTextBelowBarcode();
                // Styling a QR code and adding annotation text
                barcode.SetMargins(10);
                barcode.ChangeBarCodeColor(Color.BlueViolet);
                string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
                if (!Directory.Exists(path)) {
                    Directory.CreateDirectory(path);
                }
                string filePath = Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png");
                barcode.SaveAsPng(filePath);
                string fileName = Path.GetFileName(filePath);
                string imageUrl = $ "{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/GeneratedQRCode/" + fileName;
                ViewBag.QrCodeUri = imageUrl;
            } catch (Exception) {
                throw;
            }
            return View();
        }
    }
}


Next "Add View" right-click on the CreateQRCode action method in HomeController class. Select "Add View" then select "Razor View" next click on the "Add" button.

    In the View name CreateQRCode default name as action method in HomeController.

    Template "Create"

    In the Model, class drop-down, select GenerateQRCodeModel(GenerateQRCodeModel_Demo.Models).

    Select Add.

Following is the CreateQRCode View code.
@model GenerateQRCode_Demo.Models.GenerateQRCodeModel

@{
    ViewData["Title"] = "CreateQRCode";
}
<h1>CreateQRCode</h1>
<div class="row">
  <div class="col-md-4">
    <form asp-action="CreateQRCode">
      <div asp-validation-summary="ModelOnly" class="text-danger"></div>
      <div class="form-group">
        <label asp-for="QRCodeText" class="control-label"></label>
        <input asp-for="QRCodeText" class="form-control" />
        <span asp-validation-for="QRCodeText" class="text-danger"></span>
      </div>
      <div class="form-group">
        <input type="submit" value="Generate QR Code" class="btn btn-primary" />
      </div>
      <div class="form-group">
        <img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
      </div>
    </form>
  </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Run project Ctrl+F5


Finally, we can create QR codes using the IronBarcode library. We can save QR codes as jpg, png images, Pdf, or HTML files. We can also add a logo to our QR code file. With its high-performance levels and a vast range of capabilities available to developers working with the Portable Document Format, we prefer IronBarcode.



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 :: URL Creation Fundamentals In MVC

clock November 8, 2021 06:49 by author Peter

In this article, we are going to explore different ways of URL creation in MVC and different fundamental concepts of MVC. So let's get started with MVC fundamentals. We have two different approaches available while creating an URL in MVC framework.
    ActionLink
    Raw HTML

Action LInk in the background queries the routing engine whenever the URL associated with the given controllers ACTION. Sometimes we do have Custom URLs associated with an action, and we require to change that URL in future. For this scenario actionLink will pick up the latest URL, you don't need to make any changes.

On the other hand, if you are using raw HTML, you need to update your links when URLs changed.

As a good programmer, we should always avoid changing URLs as URLs are the public contract of your app and can be referenced by other apps, and many times users bookmark the URLs. If you change them, all these bookmarks and references will be broken.

In the end, the decision is up to the programmer's choice, no hard and fast rule here.

Again, the simplest way is using raw HTML

1: Raw HTML
Example,
<a href = "Courses/Index"> View Course</a>

2: ActionLink
Below is the example of using ActionLink for URL creation.
@HTML.ActionLink("View Courses","Index","Courses")

If the targeted action needs a parameter we can make use of an anonymous object to pass the parameter values.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1})

This will generate a link as - courses/index/1

This method doesn't generate the link for a reason, we need to pass another argument to ActionLink. This argument can be null or an anonymous object to render any additional HTML attribute.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1}, null)

We have different HTML helpers available in MVC 

Type Helper Method
ViewResult View()
PartialViewResult PartialView()
RedirectResult Redirect()
ContentResult Content()
JsonResult Json()
RedirectToRouteResult RedirectToAction()
FileResult File()
HttpNotFoundResult HttpNotFound()
EmptyResult  

Passing Data to views in MVC
We should avoid passing data using ViewData and ViewBag as these methods are fragile and need a lot of casting which makes code ugly. Instead, we can pass model or viewModel directly to view.
return View(Course);

Razor Views
@if(condition)
{
    // c# or HTML code
}


@foreach(...)
{
}


We can render a class or any attribute conditionally as follows,
@{
    var className=Model.Movies.Count >3 ? "Popular" : null;
}
<h2 class = "@className">...</h2>

Partial View

@Html.Partial("_NavBar")

Types of Routing in MVC
1: Convention based Routing

Here we can specify the routing in RouteConfig.cs file and mention the Controller, action which needs to be invoked using mapRoute method of routes collection.

2: Attribute based Routing

Here we can apply route by decorating the action method with the Route keyword followed by the path.

Authentication in MVC
Use [authorize] keyword. Apply it to action, controller or globally (in FilterConfig.cs)
Enabling Social Login in MVC

Step 1
Enable SSL: Select project, press F4, set SSL enabled to true.

Step 2
Copy SSL URL, select the project, go to properties, in the Web tab, set startup URL.

Step 3
Apply RequireSSL filter globally in FilterConfig.cs file.

Step 4
Register your app with external authentication providers to get secret key/secret. In AppStart.cs/Startup.Auth.cs, add corresponding providers and your key/secret.
Summary

In this article, we explored different ways of URL creation in MVC and different fundamental concepts of MVC. I hope you liked the article. Until Next Time - Happy Learning Cheers



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.


Month List

Tag cloud

Sign in