How to Install Bootstrap in ASP.NET MVC 5

How to Install Bootstrap in ASP.NET MVC 5

In this post, I will share the way to install Bootstrap in ASP.NET MVC5 using Visual Studio 2019

Continuing with the previous share, today I will share the way to install Bootstrap in ASP.NET MVC5 using Visual Studio 2019.

Setup Bootstrap 3.3.1 to ASP.NET MVC 5

Right-click Project -> Manager NuGet Packages -> Click icon setting configuration, add package source.

https://api.nuget.org/v3/index.json

Continue by adding a package source (following image)

You search keyword “bootstrap” and then install

You can see bootstrap in project after a successful installation.

Okay, installation is successful!

You can use bootstrap in Layout file of _Views/Shared/LayoutHome.cshtml directory. (Note you add css,javascript to file)

<link rel="stylesheet" href="~/Content/bootstrap.min.css" />  
<script src="~/Scripts/jquery-3.3.1.min.js"></script>  
<script src="~/Scripts/bootstrap.min.js"></script>  

Example - _Views/Shared/_LayoutHome.cshtml _

<!DOCTYPE html>  
<html>  
<head>  
    <meta name="viewport" content="width=device-width" />  
    <title>@ViewBag.Title</title>  
    <link rel="stylesheet" href="~/Content/bootstrap.min.css" />  
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>  
    <script src="~/Scripts/bootstrap.min.js"></script>  
</head>  
<body>  
    <div>  
        @RenderBody()  
    </div>  
</body>  
</html>  

_Views/Home/Index.cshtml _

<div class="container">  
    <div class="row">  
        <div class="col-md-12">  
            <h2>@ViewBag.title</h2>  
            <a href="https://hoanguyenit.com" class="btn btn-success">https://hoanguyenit.com</a>  
        </div>  
    </div>  
</div>  

Ok, we successfully installed bootstrap in ASP.NET MVC 5!! Thank you for reading!

ASP.NET MVC Application with JQuery, AJAX

ASP.NET MVC Application with JQuery, AJAX

Let's have a sample example: We have a submit button in our JQuery AJAX MVC application. Let's try to show a message when it is clicked. ASP.NET MVC Application - Using JQuery, AJAX

Before diving into the core topic let’s have an overview about JQuery and Ajax. What is it?

What is JQuery?
Well, JQuery is a framework (tools) for writing JavaScript, Written as "write less, do more", jQuery is to make easier to use JavaScript.

What is JavaScript?
JavaScript is an object-oriented computer programming (Scripting) language commonly used to create interactive effects within web browsers.

Let’s have a sample example:
We have a submit button in our JQuery AJAX MVC application. Let’s try to show a message when it is clicked.

Here is our button with defined id="btnSubmit":

<input type="submit" value="Create" class="btn btn-default" id="btnSubmit" />

Now we need to write some script to do that, here is some JavaScript code:

var myBtn = document.getElementById('btnSubmit');  
myBtn.addEventListener('click', function(e) {  
    e.preventDefault(); //This prevents the default action  
    alert('Hello'); //Show the alert  
});

By this code the result will show “Hello”:

Now if we can get the same result by using jQuery instead of it. Let’s have a look:

$('#btnSubmit').click(function(event) {  
    event.preventDefault(); //This prevents the default action  
    alert("Hello"); //Show the alert  
});

Note: Here use of 'e' is just a short for event which raised the event. We can pass any variable name. Notice that the ‘e’ is changed to name ‘event’ in JQuery part.

This piece of code is also producing the same result “Hello”. This is why jQuery is known as "write less, do more".

Finally the script:

<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
  
            /*var myBtn = document.getElementById('btnSubmit');  
            myBtn.addEventListener('click', function(e) {  
                e.preventDefault();  
                alert('Hello');  
            });*/
  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                alert("Hello");  
            });  
        });  
    });  
</script>

Let's focus on Ajax:

AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.

In .NET, we can call server side code using two ways:

  1. ASP .NET AJAX
  2. jQuery AJAX

In this article we will focus on JQuery Ajax.

$.ajax () Method:

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

  • $.ajax() Performs an async AJAX request.
  • $.get() Loads data from a server using an AJAX HTTP GET request.
  • $.post() Loads data from a server using an AJAX HTTP POST request.

To know more click.

$.ajax () Method Configuration option:

Options that we use:

  • async:
  • type:
  • url:
  • data:
  • datatype:
  • success:
  • error:

Let’s have details overview:

async

Set to false if the request should be sent synchronously. Defaults to true.

Note that if you set this option to false, your request will block execution of other code until the response is received.

Example:

async: false,

type

This is type of HTTP Request and accepts a valid HTTP verb.

The type of the request, "POST" or "GET" defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all the web browsers.

Example:

type: "POST",

url

The URL for the request.

Example:

url: "/Home/JqAJAX",

data

The data to be sent to the server. This can either be an object or a query string.

Example:

data: JSON.stringify(model_data),

dataType

The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.

Accepted values are text, xml, json, script, html jsonp.

Example:

dataType: "json",

contentType

This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.

Example:

contentType: 'application/json; charset=utf-8',

success

A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the DataType was JSON), as well as the text status of the request and the raw request object.

Success: function (result) {  
   $('#result').html(result);  
}

error

A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.

error: function (result) {  
   alert('Error occured!!');  
},

Let’s Post Values using JQuey,Ajax:

We often use the jQuery Ajax method in ASP.NET Razor Web Pages. Here is a sample code:

<input type="submit" id="btnSubmit" value="Add Student" />  
<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                var Student = {  
                    ID: '10001',  
                    Name: 'Shashangka',  
                    Age: 31  
                };  
                $.ajax({  
                    type: "POST",  
                    url: "/Home/JqAJAX",  
                    data: JSON.stringify(Student),  
                    dataType: "json"  
                    contentType: 'application/json; charset=utf-8',  
                    success: function(data) {  
                        alert(data.msg);  
                    },  
                    error: function() {  
                        alert("Error occured!!")  
                    }  
                });  
            });  
        });  
    });  
</script>

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Posting JSON

JSON is a data interchange format where values are converted to a string. The recommended way to create JSON is include the JSON.stringify method. In this case we have defined:

JSON.stringify(Student)

And the data type set to:

datatype: "json"

And the content type set to application/json

contentType: 'application/json; charset=utf-8'

Syntax:

JSON.stringify(value[, replacer[, space]])

Post Script:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: JSON.stringify(Student),  
    contentType: 'application/json; charset=utf-8',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

JSON Response Result:
Sent data format:
{"ID":"10001","Name":"Shashangka","Age":31}
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Objects:

To send JavaScript Objects we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default.

contentType: 'application/x-www-form-urlencoded'

Post Script

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

JavaScript Objects Response Result:

Sent data format:
ID=10001&Name=Shashangka&Age=31
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Arrays:

To send Array we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default

contentType: 'application/x-www-form-urlencoded'

Post Script:

var ID = ["Shashangka", "Shekhar", "Mandal"];  
  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: {  
        values: ID  
    },  
    datatype: "html",  
    contentType: 'application/x-www-form-urlencoded',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(string[] values) {  
    try {  
        return Json(new {  
            msg = String.Format("Fist Name: {0}", values[0])  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Array Response Result:

Sent data format:
values[]=Shashangka&values[]=Shekhar&values[]=Mandal
Received Data format:
{"msg":"Fist Name: Shashangka"}

Hope this will help to understand different datatypes and Ajax posting. Thank you!

“Visual Studio has added the full set of dependencies for ASP.NET MVC 5 to project” Can I reverse it?

By mistake I create a MVC 5 Controler instead Web Api 2 Controller in my .NET Web API Project and I received the following message:

By mistake I create a MVC 5 Controler instead Web Api 2 Controller in my .NET Web API Project and I received the following message:

Visual Studio has added the full set of dependencies for ASP.NET MVC 5 to project 'PROJECT_NAME'.
The Global.asax.cs file in the project may require additional changes to enable ASP.NET MVC.
  1. Add the following namespace references:
  2. using System.Web.Mvc; using System.Web.Routing; using System.Web.Optimization;
  3. If the code does not already define an Application_Start method, add the following method:
  4. protected void Application_Start() { }
  5. Add the following lines to the end of the Application_Start method:
  6. AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); BundleConfig.RegisterBundles(BundleTable.Bundles);

Is there a simple way to reverse this? Do I have to delete unnecessary files and dependencies one by one manually? Will previously created Api controllers work without changes?

Any help or assistance would be greatly appreciated.

Create Login and Registration in Your ASP.NET Core MVC App

Create Login and Registration in Your ASP.NET Core MVC App

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

User authentication and authorization are common features in web applications, but building these mechanics has the potential to take a lot of time. Doing so requires setting up persistent storage for user information (in some type of database) and paying keen attention to potential security issues around sensitive operations like hashing passwords, password reset workflows, etc. - weeks of development time begin to add up before we ever get to the functionality that delivers value to your users.

In this post, we’ll walk through how Okta simplifies this process for us and set up a simple integration for an ASP.NET Core MVC app using the Okta NuGet package. We’ll build functionality for users to register for new accounts and login with their Okta credentials.

Scaffold Your ASP.NET Project

To follow along with this tutorial start by creating a new app in the console:

mkdir MyOktaProject
cd MyOktaProject
dotnet new mvc


Configure User Registration

If you don’t already have one, you’ll need to create an Okta developer account. Doing so will give you a URL for your organization called an “Okta domain”. It will also allow you to create your login credentials for accessing the Okta dashboard.

Upon submission of this form, you will receive an email Okta with instructions to obtain your credentials and complete your registration.

Execute the following steps to configure Okta so that users can register themselves for an account.

  1. From the Administrative Dashboard, hover over Users and click Registration
  2. Click Enable Registration
  3. Save the changes

Configure Basic User Authentication

Once you have access to your account you can proceed to the Dashboard using a link like the one below:

<span

class="okta-preview-domain">https://{yourOktaDomain}/admin/dashboard

On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application.

Select Web then click Next.

On the Create New Application screen, set the following values:

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values:

Logout redirect URIs: https://localhost:5001/signout-callback-oidc

Initiate login URI: https://localhost:5001/authorization-code/callback

Add .NET Authentication Dependencies

Once your account is set up you need to add the Okta.Sdk library to your project. This post will take the approach of using the NuGet package, but the Github repository for Okta.AspNetCore can be found here.

To proceed simply search for the latest version of the Okta.Sdk NuGet package in your IDE of choice (version 1.2.0 at the time of this publication) and install it. If you’re using Visual Studio you can do this by right-clicking on the project in the solution explorer and selecting Manage NuGet Packages. For those of you not using Visual Studio, add the package via console window using the following command:

dotnet add package Okta.Sdk --version 1.2.0


Configure Your ASP.NET App for Login

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you configured above.

Add the following code to your appsettings.json file:

  "Okta": {
    "Issuer": "https://{yourOktaDomain}/oauth2/default",
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}"
  }


You can find each of the actual values needed to replace the settings in the config above in the following places:

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page

Add some using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;


Add the following code to the top of the ConfigureServices method in your Startup.cs file:

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ClientId = Configuration["okta:ClientId"];
        options.ClientSecret = Configuration["okta:ClientSecret"];
        options.Authority = Configuration["okta:Issuer"];
        options.CallbackPath = "/authorization-code/callback";
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.UseTokenLifetime = false;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name"
        };
    });


In the Configure() method of your Startup.cs file add this line just before the app.UseMvc() method:

app.UseAuthentication();


Add the following MeViewModel to the Models directory:

using System.Collections.Generic;

namespace OktaAspNetCoreMvc.Models
{
    public class MeViewModel
    {
        public string Username { get; set; }

        public bool SdkAvailable { get; set; }

        public dynamic UserInfo { get; set; }

        public IEnumerable<string> Groups { get; set; }
    }
}


Add Login to Your ASP.NET App

Now that all the configuration and plumbing is done, you’re ready to add the code that will actually log users into your application.

Add the following AccountController to the Controller directory.

The controller exposes the Login() action. If the user has already been authenticated, the Login() action will redirect them to the home page. Otherwise, it will redirect them to the Okta login screen.

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
using Okta.Sdk;

namespace OktaAspNetCoreMvc.Controllers
{
    public class AccountController : Controller
    {
        private readonly IOktaClient _oktaClient;

        public AccountController(IOktaClient oktaClient = null)
        {
            _oktaClient = oktaClient;
        }

        public IActionResult Login()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return Challenge(OpenIdConnectDefaults.AuthenticationScheme);
            }

            return RedirectToAction("Index", "Home");
        }
    }
}


Add the following code to your _Layout.cshtml file, just below the main menu to add the login button, or a welcome message, based on the current user’s status.:

   @if (User.Identity.IsAuthenticated)
    {
        <ul class="nav navbar-nav navbar-right">
            <li><p class="navbar-text">Hello, @User.Identity.Name</p></li>
        </ul>
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li><a asp-controller="Account" asp-action="Login">Log in</a></li>
        </ul>
    }


For information on user authorization using Okta groups check out Lee Brandt’s article on user authorization in ASP.NET Core with Okta.

Register Users

If you following the instructions above to enable self-service registration the “Don’t have an account? Sign Up” message will appear at the bottom of the login form. In the next step, you’ll run the application.

Log In Using ASP.NET

That’s it! To run your solution open up a terminal and enter the following command:

dotnet run


Then navigate to http://localhost:5001 in your browser and enjoy!

The source code for this tutorial is available on GitHub.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

Learn More

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

ASP NET Core (ASP.NET 5),MVC 6,C#,Angular2 & EF Crash Course

Rest Api’s in Asp.Net and C#

Hands on ASP .Net Core 2