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 ASP.NET MVC, Create a Simple Login Application That Makes use of Sessions

clock November 3, 2023 08:45 by author Peter

1. Create your database
Using the following script, create the UserProfile table

CREATE TABLE UserProfile
(
    UserId INT PRIMARY KEY IDENTITY(1, 1),
    UserName VARCHAR(50),
    Password VARCHAR(50),
    IsActive BIT
);

Insert user records using the following script:
INSERT INTO UserProfile (UserName, Password, IsActive)
VALUES ('Peter', 'Peter1234', 1),
       ('Scott', 'Scott1234', 1),
       ('Alex', 'Alex1234', 1);

2. Create Project
Go to File, New, then click on Project.

Select Visual C#, Web under Installed templates. After that, select ASP.NET MVC 4 Web Application, then mention the Application Name (MvcLoginAppDemo) and Solution Name as you wish, then click OK.

Under Project template, select a template as Basic, then view the engine as Razor. Click OK.

3. Include an Entity Data Model
Navigate to Solution Explorer, select Project, Add, and then ADO.NET Entity Data Model.

Give it a meaningful model name, and then click on Add.

Select Generate from the database and then click on Next.

Click on New Connection.

After clicking on New Connection, we have to provide the following Connection Properties in the following wizard.

Provide the Server name.

  • Select the "Use SQL Server Authentication" radio button.
  • Enter the Username and Password in the password text box.
  • Check the "Save my password" checkbox.
  • Select the "Select or enter a database name:" radio button.
  • Select the database to which you want to set the connection.
  • Click on the "Test Connection" button to ensure the connection can be established.
  • Then click OK.

Select the radio button, and yes, include the sensitive data in the connection string.

Choose your database objects, as in the following image.

Click on Finish. At this point UserProfie entity will be created.

4. Add a Controller
Go to Solution Explorer, right-click on the Controller folder, Add, and then click on Controller.
( Or ) Simply use shortcut key Ctrl + M, Ctrl + C,


Provide the Controller Name and Scaffolding template as Empty MVC Controller. Then click on Add.

Write the following code in HomeController.
using System.Linq;
using System.Web.Mvc;

namespace MvcLoginAppDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(UserProfile objUser)
        {
            if (ModelState.IsValid)
            {
                using (DB_Entities db = new DB_Entities())
                {
                    var obj = db.UserProfiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();
                    if (obj != null)
                    {
                        Session["UserID"] = obj.UserId.ToString();
                        Session["UserName"] = obj.UserName.ToString();
                        return RedirectToAction("UserDashBoard");
                    }
                }
            }
            return View(objUser);
        }

        public ActionResult UserDashBoard()
        {
            if (Session["UserID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Login");
            }
        }
    }
}


5. Create Views

Create View for Login Action Method
Right-click on the Login Action method, then click on Add View, as in the following picture.

Create a Strongly Typed View

View Name must be an action method name.
Select the view engine as Razor.
Select Create a strongly typed view CheckBox.
Select Model class as UserProfile (MvcLoginAppDemo)
Select the Scaffold template as Empty
Click on Add

Write the following code in Login.cshtml (view).
@model MvcLoginAppDemo.UserProfile

@{
    ViewBag.Title = "Login";
}

@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
    <fieldset>
        <legend>Mvc Simple Login Application Demo</legend>

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        @if (ViewBag.Message != null)
        {
            <p style="border: 1px solid red">
                @ViewBag.Message
            </p>
        }

        <table>
            <tr>
                <td>@Html.LabelFor(a => a.UserName)</td>
                <td>@Html.TextBoxFor(a => a.UserName)</td>
                <td>@Html.ValidationMessageFor(a => a.UserName)</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(a => a.Password)</td>
                <td>@Html.PasswordFor(a => a.Password)</td>
                <td>@Html.ValidationMessageFor(a => a.Password)</td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Login" /></td>
                <td></td>
            </tr>
        </table>
    </fieldset>
}

Create View for UserDashBoard Action method same as login view. And write the following code in UserDashBoard.cshtml (View).
@{
    ViewBag.Title = "UserDashboard";
}

<fieldset>
    <legend>User Dashboard</legend>

    @if (Session["UserName"] != null)
    {
        <text>Welcome @Session["UserName"].ToString()</text>
    }
</fieldset>


6. Set as StartUp Page
Go to Solution Explorer, Project, App_Start, then RouteConfig.cs, and change the action name from Index to Login (Login. cshtml as start-up page).

7. Run the Application

Provide the user credentials and click on OK. If you provide valid user credentials, then the user name will be displayed on your dashboard.




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Security ASP.net Core MVC (C#) Encryption and Decryption

clock September 20, 2023 07:27 by author Peter

Harnessing the power of C# to enhance our data security through encryption and decryption is a versatile and necessary feature in the world of ASP.NET Core MVC. This security boost is made possible by the use of a variety of encryption methods, including but not limited to AES (Advanced Encryption Standard), RSA (Rivest-Shamir-Adleman), DES (Data Encryption Standard), and others. These cryptographic algorithms enable developers to protect sensitive information while keeping it secure and tamper-resistant.

Let's look at how the AES algorithm, recognized for its strong encryption capabilities, may be smoothly integrated into our ASP.NET Core MVC application to encrypt and decrypt data. This example provides a baseline understanding of encryption processes within the ASP.NET Core MVC framework, allowing developers to begin exploring and implementing sophisticated security features in their web applications.

We'll have a better understanding of how to use the AES algorithm in our ASP.NET Core MVC projects by the end of this demonstration, enhancing our capacity to secure and protect key data assets. This knowledge enables us to make informed judgments about which encryption approaches best suit our application's particular security requirements, assuring the highest level of protection for our users' sensitive data.

Step 1: Create an Encryption/Decryption Helper Class.
To carry out encryption and decryption operations within our program, it is generally advised that we construct a specialized helper class. Here's an example of a well-structured class that can be utilized to improve the security of our application.

using System.Security.Cryptography;

namespace ZR.CodeExample.SecureMVC.Helpers
{
    public static class EncryptionHelper
    {
        private static readonly string EncryptionKey = GenerateRandomKey(256);

        public static string Encrypt(string plainText)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Convert.FromBase64String(EncryptionKey);
                aesAlg.IV = GenerateRandomIV(); // Generate a random IV for each encryption

                aesAlg.Padding = PaddingMode.PKCS7; // Set the padding mode to PKCS7

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                    }
                    return Convert.ToBase64String(aesAlg.IV.Concat(msEncrypt.ToArray()).ToArray());
                }
            }
        }


        public static string Decrypt(string cipherText)
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Convert.FromBase64String(EncryptionKey);
                aesAlg.IV = cipherBytes.Take(16).ToArray();

                aesAlg.Padding = PaddingMode.PKCS7; // Set the padding mode to PKCS7

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(cipherBytes, 16, cipherBytes.Length - 16))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            return srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
        }

        private static byte[] GenerateRandomIV()
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.GenerateIV();
                return aesAlg.IV;
            }
        }

        private static string GenerateRandomKey(int keySizeInBits)
        {
            // Convert the key size to bytes
            int keySizeInBytes = keySizeInBits / 8;

            // Create a byte array to hold the random key
            byte[] keyBytes = new byte[keySizeInBytes];

            // Use a cryptographic random number generator to fill the byte array
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(keyBytes);
            }

            // Convert the byte array to a base64-encoded string for storage
            return Convert.ToBase64String(keyBytes);
        }

    }
}

This helper class contains the encryption and decryption functionality, as the name implies, making it easy to secure sensitive data in our ASP.NET Core MVC application. As part of best practices, we produce the encryption key dynamically. GenerateRandomKey(256)

We improve the security of our application by isolating the encryption and decryption code in a dedicated helper class. This method enables us to quickly handle sensitive data within our ASP.NET Core MVC application, adding an additional degree of security.

Step 2: Encryption and decryption are used in our controller or service
To use the encryption and decryption capabilities we've incorporated, we'll need to call the Encrypt and Decrypt methods within our controller or service class. Here's a detailed example on how to accomplish it.

using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using ZR.CodeExample.SecureMVC.Helpers;
using ZR.CodeExample.SecureMVC.Models;

namespace ZR.CodeExample.SecureMVC.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            // Define the data you want to secure
            string plainText = "I am Peter from United Kingdom";

            // Encrypt the data using the EncryptionHelper
            string cipherText = EncryptionHelper.Encrypt(plainText);

            // Decrypt the data to retrieve the original content
            string decryptedText = EncryptionHelper.Decrypt(cipherText);

            // Store the encrypted and decrypted data in ViewData for use in your view
            ViewData["CipherText"] = cipherText;
            ViewData["DecryptedText"] = decryptedText;

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Step 3: In the View, show both encrypted and decrypted data
One of the most impressive characteristics of Razor views is their ability to display both encrypted and decrypted data from our controller's ViewData dictionary. We can successfully provide sensitive information to our users in a secure manner by exploiting this feature. Let's look at an example of how this can be done within a Razor view.

@{
    ViewData["Title"] = "Security ASP.net Core MVC (C#) Encryption and Decryption";
}

<div class="text-center">
    <h1 class="display-4">@ViewData["Title"]</h1>
    <p>By Peter, delve into the intricacies of security in ASP.NET Core MVC (C#) through our comprehensive article, focusing on the vital aspects of encryption and decryption techniques. Learn how to safeguard your web applications effectively.</p>
</div>
<div>
    <h2>Encrypted Text:</h2>
    <p>@ViewData["CipherText"]</p>
</div>

<div>
    <h2>Decrypted Text:</h2>
    <p>@ViewData["DecryptedText"]</p>
</div>
<div>
    <h3>Who is Peter</h3>
    <p>I am 
Peter, a seasoned Technical Lead Developer </p>
</div>

We'll suppose in this code snippet that our controller action is coupled with a view, such as Index.cshtml. We may display the encrypted and decrypted content on the web page by using this Razor view. Furthermore, we have the ability to modify the HTML structure and styling to match the design and requirements of our application.




ASP.NET MVC Hosting - HostForLIFEASP.NET :: A Simple Architecture for Developing Web Applications Using ASP.NET Core MVC C#

clock September 14, 2023 06:59 by author Peter

When paired with the Clean Architecture pattern, ASP.NET Core MVC provides a solid framework for building online applications that can result in controllable and extendable solutions. In this article, we will look at how to organize an ASP.NET Core MVC project utilizing Clean Architecture principles, using C# code samples.

What is the Clean Architecture Concept?
Clean Architecture is a software design philosophy that emphasizes concern separation and maintainability by layering the codebase. Typically, these layers include.

Layer of User Interface
The presentation elements are placed here. It includes controllers, views, and view models in the context of ASP.NET Core MVC.

Layer of Application
This layer contains the application's business logic. It is in charge of managing user queries, data processing, and interfacing with the domain layer.

The Domain Layer
This layer is the application's heart, defining the fundamental business entities, rules, and domain-specific logic. It must be decoupled from any infrastructure or application-specific code.

Layer of Infrastructure
This layer handles external concerns like data access, external services, and infrastructure-related code. It should be kept separate from the other layers.

Establishing a Clean Architecture Initiative
Let's get started by making a new ASP.NET Core MVC project with Clean Architecture in mind.

Step One: Make a New ASP.NET Core MVC Project

To start a new ASP.NET Core MVC project, we can use either the dotnet command-line tool or Visual Studio. Ascertain that the ASP.NET Core SDK is installed.

dotnet new mvc -n ZRCleanArchitectureApp

Step 2: Creating a Project Structure
Separate our project into distinct folders for each layer to better organize it.

ZRCleanArchitectureApp.Web
This folder comprises controllers, views, and view models and represents the presentation layer.

ZRCleanArchitectureApp.Application

We define application services and business logic in this subdirectory.

ZRCleanArchitectureApp.Domain
This folder contains the definitions of our domain entities and business rules.

ZRCleanArchitectureApp.Infrastructure

This section handles data access, external services, and infrastructure-related code.

Step 3: Put Clean Architecture into Practice
Domain Entities Definition

// ZRCleanArchitectureApp.Domain/Entities/Product.cs
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}


Implementing Application Services
// ZRCleanArchitectureApp.Application/Services/ProductService.cs
public class ProductService
{
    private readonly IProductRepository _productRepository;

    public ProductService(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    public async Task<IEnumerable<Product>> GetAllProductsAsync()
    {
        return await _productRepository.GetAllAsync();
    }

    // Add other business logic methods here
}


Creating Controllers
// ZRCleanArchitectureApp.Web/Controllers/ProductController.cs
public class ProductController : Controller
{
    private readonly ProductService _productService;

    public ProductController(ProductService productService)
    {
        _productService = productService;
    }

    public async Task<IActionResult> Index()
    {
        var products = await _productService.GetAllProductsAsync();
        return View(products);
    }

    // Add other action methods
}


Configuring Dependency Injection
In the Program.cs file, configure dependency injection for our services and repositories.
builder.Services.AddScoped<ProductService>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();

ASP.NET Core MVC Clean Architecture provides a disciplined approach to designing maintainable, scalable, and easily testable web applications. We may focus on building clean, modular code by dividing concerns into discrete levels.

We have barely scraped the surface of Clean Architecture in this post. We may improve our project by incorporating validation, authentication, and authorization systems, as well as unit tests to check the accuracy of our code.

Keep in mind that Clean Architecture is a suggestion, not a hard and fast rule. Adapt it to our project's unique requirements and complexities, and strive for simplicity and maintainability in our codebase at all times.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Implementing AJAX for Editing Data and Updating the Database in ASP.NET MVC

clock August 7, 2023 10:56 by author Peter

Introduction: In this article, we will explore how to use AJAX to implement an edit functionality for student data in an ASP.NET MVC application. We'll demonstrate how to utilize jQuery AJAX to fetch the data from the server, populate an edit modal form, allow the user to make changes, and then update the database with the modified data. The provided code showcases a simple implementation that can serve as a foundation for more advanced data editing and updating tasks.


To follow along with this tutorial, you should have a basic understanding of ASP.NET MVC, C#, jQuery, and Entity Framework.

Overview of the Code
The code example consists of three main parts: the jQuery AJAX function in JavaScript, the ASP.NET MVC controller method, and the repository class responsible for database operations.

jQuery AJAX Function (Edit Function)
The editStudent(ID) function is responsible for making an AJAX request to the server to retrieve the student data for editing. It uses jQuery's $.ajax() method to send a GET request to the server, passing the student ID as a parameter.
function editStudent(ID) {
    $.ajax({
        url: '/Home/EditStudent/' + ID,
        type: 'get',
        success: function (response) {
            $("#EditModal").html(response);
        },
        error: function (xhr, textStatus, error) {
            // Handle error response
        }
    });
    console.log("edit: " + ID);
}


ASP.NET MVC Controller Method
The HomeController class acts as the controller responsible for handling incoming requests. The EditStudent(int ID) action method is designed to receive the student ID sent by the AJAX function and fetch the student data from the repository.
public class HomeController : Controller
{
    OperationRepositery repo = null;

    public HomeController()
    {
        repo = new OperationRepositery();
    }

    public ActionResult EditStudent(int ID)
    {
        var result = repo.EditFunction(ID);
        return View(result);
    }
}

Repository Class (Edit Method)
The OperationRepositery class encapsulates the data access logic and implements the EditFunction(int ID) method to fetch the student data from the database using Entity Framework.
public class OperationRepositery
{
    public StudentModel EditFunction(int ID)
    {
        using (var context = new StudentEntities())
        {
            var resultEdit = context.StudentTable.Where(x => x.ID == ID).Select(x => new StudentModel()
            {
                ID = x.ID,
                Student = x.Student,
                School = x.School,
                Marks = x.Mark,
                Rank = x.Rank,
                Course = x.Stream,
                Country = x.Country,
                State = x.State,
                City = x.City,
                LanguageIds = x.Languages
            }).FirstOrDefault();

            return resultEdit;
        }
    }
}


In this article, we have learned how to use AJAX to implement the edit functionality for student data in an ASP.NET MVC application. The JavaScript AJAX function communicates with the server to fetch the data, and the ASP.NET MVC controller receives the request and retrieves the student data from the repository class. Developers can use this example as a starting point to implement more advanced features, such as validation, error handling, or additional data manipulation before updating the database. Remember to implement security measures and validate user input to protect the application from potential vulnerabilities. Happy coding!



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Implement Multiselect Checkboxes in ASP.NET MVC Using AJAX?

clock August 4, 2023 07:40 by author Peter

In this tutorial, we will look at how to create a dynamic form with multiselect checkboxes in an ASP.NET MVC application. We'll concentrate on how to use jQuery AJAX to handle form submission, retrieve the selected checkboxes, and store the data to the database. The code provided offers a detailed example of how to develop a user-friendly student data management system that allows each student to select several languages.


You should have a basic understanding of ASP.NET MVC, C#, jQuery, and Entity Framework before going.

How do you make a Multiselect Checkbox Form?

In the "Index.chtml" file, we have designed a form to collect student data, including a section to select multiple languages for each student using checkboxes.
<!-- Index.chtml -->
<!-- ... (existing code) ... -->
<div class="text-light text-center my-3">
    <div class="d-flex justify-content-center">
        <h5 class="text-warning">Languages:</h5>
        <div id="languagesSection">
            @for (int i = 0; i < Model.Languages.Count; i++)
            {
                <label>@Model.Languages[i].LanguageName</label>
                @Html.CheckBoxFor(model => model.Languages[i].IsChecked)
                @Html.HiddenFor(model => model.Languages[i].ID)
                @Html.HiddenFor(model => model.Languages[i].LanguageName)
            }
        </div>
    </div>
</div>
<!-- ... (existing code) ... -->

Implementing AJAX for Adding Data to Database
In the JavaScript section, we've implemented an AJAX function to handle the form submission and add student data to the database.
// AJAX for Adding Data to Database
$("#SumbitButton").click(function () {
    var selected = []; // initialize array
    $('div#languagesSection2 input[type=checkbox]').each(function () {
        if ($(this).is(":checked")) {
            selected.push($(this).attr("id"));
        }
    });

    $("#Languages").val(selected);
    var studentData = $("#studentInputForm").serialize();

    if (!$('#studentInputForm').valid()) {
        return false;
    }

    $.ajax({
        url: "/Home/SaveStudent",
        type: "POST",
        data: studentData,
        success: function (data) {
            $('#studentInputForm').find(':input').val('');
            $('input[type=checkbox]').prop('checked', false);
        },
        error: function (errormessage) {
            console.log("error message");
        }
    });
});

Handling the AJAX Request in the Controller
In the "HomeController," we've added two action methods, one for saving student data and the other for handling the edit functionality.
public class HomeController : Controller
{
    OperationRepositery repo = null;
    public HomeController()
    {
        repo = new OperationRepositery();
    }

    public ActionResult Index()
        {
            StudentModel model = new StudentModel();
            model.Languages = db.LanguagesTable.Select(lang => new LanguagesModel
            {
                ID = lang.ID,
                LanguageName = lang.LanguagesName,
            }).ToList();
            return View(model);
        }

    // Action method for adding student data
    public ActionResult SaveStudent(StudentModel model)
    {
        var result = repo.AddData(model);
        return Json(new { result = true }, JsonRequestBehavior.AllowGet);
    }

    // Action method for handling the edit functionality
    public ActionResult EditStudent(int ID)
    {
        var result = repo.EditFunction(ID);
        var languageIdList = result.LanguageIds.Split(',').Select(x => Convert.ToInt32(x)).ToList();
        result.Languages = db.LanguagesTable.Select(x => new LanguagesModel
        {
            ID = x.ID,
            LanguageName = x.LanguagesName,
            IsChecked = languageIdList.Contains(x.ID)
        }).ToList();
        return View(result);
    }
}


Happy coding!



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Implement Multiselect Checkboxes in ASP.NET MVC Using AJAX?

clock August 4, 2023 07:17 by author Peter

We will explore how to implement a dynamic form with multiselect checkboxes in an ASP.NET MVC application. We'll focus on using jQuery AJAX to handle the form submission, retrieve the selected checkboxes, and save the data to the database. The provided code includes a complete example of how to create a user-friendly student data management system with the ability to select multiple languages for each student.


Before proceeding, you should have a basic understanding of ASP.NET MVC, C#, jQuery, and Entity Framework.
How to create the Multiselect Checkbox Form?

In the "Index.chtml" file, we have designed a form to collect student data, including a section to select multiple languages for each student using checkboxes.
<!-- Index.chtml -->
<!-- ... (existing code) ... -->
<div class="text-light text-center my-3">
    <div class="d-flex justify-content-center">
        <h5 class="text-warning">Languages:</h5>
        <div id="languagesSection">
            @for (int i = 0; i < Model.Languages.Count; i++)
            {
                <label>@Model.Languages[i].LanguageName</label>
                @Html.CheckBoxFor(model => model.Languages[i].IsChecked)
                @Html.HiddenFor(model => model.Languages[i].ID)
                @Html.HiddenFor(model => model.Languages[i].LanguageName)
            }
        </div>
    </div>
</div>
<!-- ... (existing code) ... -->

Implementing AJAX for Adding Data to Database
In the JavaScript section, we've implemented an AJAX function to handle the form submission and add student data to the database.
// AJAX for Adding Data to Database
$("#SumbitButton").click(function () {
    var selected = []; // initialize array
    $('div#languagesSection2 input[type=checkbox]').each(function () {
        if ($(this).is(":checked")) {
            selected.push($(this).attr("id"));
        }
    });

    $("#Languages").val(selected);
    var studentData = $("#studentInputForm").serialize();

    if (!$('#studentInputForm').valid()) {
        return false;
    }

    $.ajax({
        url: "/Home/SaveStudent",
        type: "POST",
        data: studentData,
        success: function (data) {
            $('#studentInputForm').find(':input').val('');
            $('input[type=checkbox]').prop('checked', false);
        },
        error: function (errormessage) {
            console.log("error message");
        }
    });
});

Handling the AJAX Request in the Controller
In the "HomeController," we've added two action methods, one for saving student data and the other for handling the edit functionality.
public class HomeController : Controller
{
    OperationRepositery repo = null;
    public HomeController()
    {
        repo = new OperationRepositery();
    }

    public ActionResult Index()
        {
            StudentModel model = new StudentModel();
            model.Languages = db.LanguagesTable.Select(lang => new LanguagesModel
            {
                ID = lang.ID,
                LanguageName = lang.LanguagesName,
            }).ToList();
            return View(model);
        }

    // Action method for adding student data
    public ActionResult SaveStudent(StudentModel model)
    {
        var result = repo.AddData(model);
        return Json(new { result = true }, JsonRequestBehavior.AllowGet);
    }

    // Action method for handling the edit functionality
    public ActionResult EditStudent(int ID)
    {
        var result = repo.EditFunction(ID);
        var languageIdList = result.LanguageIds.Split(',').Select(x => Convert.ToInt32(x)).ToList();
        result.Languages = db.LanguagesTable.Select(x => new LanguagesModel
        {
            ID = x.ID,
            LanguageName = x.LanguagesName,
            IsChecked = languageIdList.Contains(x.ID)
        }).ToList();
        return View(result);
    }
}


Happy coding!



ASP.NET MVC Hosting - HostForLIFEASP.NET :: MVC Crud Using Generic Repository And jQuery

clock June 28, 2023 10:46 by author Peter

It’s good idea to stay on the same page while performing create, update, and delete operations. There are many ways to do it such as making them partial views, using Bootstrap’s model popup, loading partial views, using AJAX etc. However, In this post, we will learn how to do it, using jQuery, Generic Repository Pattern, and Entity Framework code first migration.


Repository Pattern
Repository mediates between the domain and the data mapping layers, using a collection-like interface to access the domain objects.

Getting started,

Step 1 Create MVC Application
Open Visual Studio to create a new project, followed by selecting ASP.NET Web Application and name mvc_crud and click OK. In the templatesSelectMvc template and keep the authentication off.

Step 2
Install Entity Framework and fluent validation through NuGet Package.

Step 3 Add Model Class
Now, add new class under models and name it as employee class.
    namespacemvc_CRUD.Models {  
        publicclassEmployee {  
            publicint Id {  
                get;  
                set;  
            }  
            publicstring Phone {  
                get;  
                set;  
            }  
            publicstringFirstName {  
                get;  
                set;  
            }  
            publicstringLastName {  
                get;  
                set;  
            }  
            publicstring Email {  
                get;  
                set;  
            }  
            publicDepartmentDepartment {  
                get;  
                set;  
            }  
            publicGenderGender {  
                get;  
                set;  
            }  
            publicboolIsActive {  
                get;  
                set;  
            }  
        }  
    }  
    publicenumDepartment {  
        Sales,  
        Management,  
        Security  
    }  
    publicenumGender {  
        Male,  
        Female  
    }  

Step 4 Create validation class
Create new folder validation. Afterwards, right click on validation folder and add new class, name it EmployeeValidation.
    publicclassEmployeeValidation AbstractValidator < Employee > {  
        publicEmployeeValidation() {  
            RuleFor(e => e.FirstName).NotEmpty().Length(0, 8);  
            RuleFor(e => e.LastName).NotEmpty().Length(0, 8);  
            RuleFor(e => e.Phone).Length(10).WithMessage("Enter valid number");  
            RuleFor(s => s.Email).NotEmpty().WithMessage("Email address is required").EmailAddress().WithMessage("A valid email is required");  
        }  
    }  


Step 5 Create DbContext class
Now, let’s create a new folder, DAL. Afterwards, add new class, which is derived from DbContext and name it EmployeeContext.
    publicclassEmployeeContext DbContext {  
        publicEmployeeContext()  
        base("EmployeeDB") {}  
        publicDbSet < Employee > Empoyees {  
            get;  
            set;  
        }  
    }  

Step 6 Create Repository Interface class
Now, let’s add a new generic interface, IRepositoryunder abstract folder .
    publicinterfaceIRepository < T > whereT class {  
        IEnumerable < T > GetAll();  
        TFindBy(object id);  
        void Add(Tobj);  
        void Update(Tobj);  
        void Delete(object id);  
        void Save();  
    }  

Step 7 Create Repository Base class

Now, we are going to add an abstract class RepositoryBase, which has virtual implementation on IRepositary interface. For every other Repository, we will add later, which will inherit this abstract class by overriding the virtual methods.
    publicabstractclassRepositoryBase < T > whereT class {  
        protectedEmployeeContext _context;  
        protectedDbSet < T > dbSet;  
        publicRepositoryBase() {  
            this._context = newEmployeeContext();  
            dbSet = _context.Set < T > ();  
        }  
        publicRepositoryBase(EmployeeContext _dataContext) {  
            this._context = _dataContext;  
            dbSet = _dataContext.Set < T > ();  
        }  
        publicvirtualIEnumerable < T > GetAll() {  
            returndbSet.ToList();  
        }  
        publicTFindBy(object id) {  
            returndbSet.Find(id);  
        }  
        publicvirtualvoid Add(Tobj) {  
            dbSet.Add(obj);  
        }  
        publicvirtualvoid Update(Tobj) {  
            dbSet.Attach(obj);  
            _context.Entry(obj).State = EntityState.Modified;  
        }  
        publicvirtualvoid Delete(object id) {  
            T existing = dbSet.Find(id);  
            dbSet.Remove(existing);  
        }  
        publicvirtualvoid Save() {  
            _context.SaveChanges();  
        }  
    }  


Step 8 Create Repository class
Now, let’s create a new folder repository. Afterwards, add new class EmployeeRepository class, which will inherit from Abstract but with a generic repository base andIEmployeeRepository interface.
    namespacemvc_CRUD.Repository {  
        publicclassEmployeeRepository RepositoryBase < Employee > , IEmployeeRepository {}  
        publicinterfaceIEmployeeRepository IRepository < Employee > {}  
    }  

Step 9 Add connection string
Now, add the connection string in web.config file.
    <connectionStrings>  
        <addname="EmployeeDB" connectionString="Data Source=.\SQLEXPRESS;InitialCatalog=EmployeeDB;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" /> </connectionStrings>  


Step 10
In the packet manager console, run the commands given below.
enable-migrations

add-migration "initial-migration"

update-database -verbose

Step 11 Add Controller class
Now, let’s EditHomeController and add the code given below.
    publicclassHomeController Controller {  
        publicreadonlyIEmployeeRepository _employeeRepository;  
        publicHomeController(IEmployeeRepository _employeeRepository) {  
            this._employeeRepository = _employeeRepository;  
        }  
        publicActionResult Index() {  
            varemp = _employeeRepository.GetAll();  
            return View(emp);  
        }  
        publicActionResult Create() {  
                return View();  
            }  
            [HttpPost]  
        publicActionResult Create(Employeeobj) {  
                EmployeeValidationval = newEmployeeValidation();  
                ValidationResult model = val.Validate(obj);  
                if (model.IsValid) {  
                    _employeeRepository.Add(obj);  
                    _employeeRepository.Save();  
                } else {  
                    foreach(ValidationFailure _error inmodel.Errors) {  
                        ModelState.AddModelError(_error.PropertyName, _error.ErrorMessage);  
                    }  
                }  
                return View(obj);  
            }  
            // GET Employees/Edit/5  
        publicActionResult Update(int id) {  
                varemp = _employeeRepository.FindBy(id);  
                return View(emp);  
            }  
            [HttpPost]  
            [ValidateAntiForgeryToken]  
        publicActionResult Update(Employeeemp) {  
                if (ModelState.IsValid) {  
                    _employeeRepository.Update(emp);  
                    _employeeRepository.Save();  
                    returnRedirectToAction("Index");  
                }  
                return View(emp);  
            }  
            // GET Employees/Delete/5  
        publicActionResult Delete(int id) {  
                varemp = _employeeRepository.FindBy(id);  
                return View(emp);  
            }  
            [HttpPost, ActionName("Delete")]  
            [ValidateAntiForgeryToken]  
        publicActionResultDeleteConfirmed(int id) {  
            _employeeRepository.Delete(id);  
            _employeeRepository.Save();  
            returnRedirectToAction("Index");  
        }  
    }  

Step 12 Add Dependency Container
Before we generate views, let’s add a Dependency container. Install UnityMvc5 through NuGet Package and edit the unityConfig class in the App_Start folder.
    publicstaticclassUnityConfig {  
        publicstaticvoidRegisterComponents() {  
            var container = newUnityContainer();  
            // register all your components with the container here  
            // it is NOT necessary to register your controllers  
            // e.g. container.RegisterType<ITestService, TestService>();  
            container.RegisterType < IEmployeeRepository, EmployeeRepository > ();  
            DependencyResolver.SetResolver(newUnityDependencyResolver(container));  
        }  
    }  


Register in the global.asax file
    UnityConfig.RegisterComponents();  

Step 13 Add Index view
Now, let’s add Index view. Right click inside the action method and then click add view, followed by selecting the create strongly-typed view.

We will use the index to load the other pages, using jQuery but before it, lets get jqueryreveal. Here, we need the jqueryreveal.js and reveal.css files to render in the layout. Afterwards, add the create, update, and delete views.
    @model IEnumerable<mvc_CRUD.Models.Employee>  
    @{  
        ViewBag.Title = "Index";  
    }  
    <div id="main_div" class="panel panel-primary">  <div class="panel-heading">Employee List</div>  
        <div class="panel-body">  
            <div class="col-md-6"><a href="#" data-reveal-id="Create" class="CreateBtn"><i class="glyphicon glyphicon-file">Add</i></a><br />         </div>  
            <div class="table table-responsive">  
                <table class="table table-striped table-condensed flip-content">  
                    <thead class="flip-content">  
                        <tr>  
                            <th>Phone</th>  
                            <th>First name</th>  
                            <th>Last name</th>  
                            <th>Email</th>  
                            <th>Department</th>  
                            <th>Gender</th>  
                            <th>Is Active</th>  
                            <th></th>  
                        </tr>  
                    </thead>  
                    <tbody>  
                        @foreach (var item in Model)  
                        {  
                           <tr>  
                                <td> @Html.DisplayFor(modelItem => item.Phone) </td>  
                                <td> @Html.DisplayFor(modelItem => item.FirstName) </td>  
                                <td> @Html.DisplayFor(modelItem => item.LastName) </td>  
                                <td> @Html.DisplayFor(modelItem => item.Email)</td>  
                                <td>@Html.DisplayFor(modelItem => item.Department) </td>  
                                <td> @Html.DisplayFor(modelItem => item.Gender) </td>  
                                <td> @Html.DisplayFor(modelItem => item.IsActive)</td>  
                             <td>  
                          <a href="#" id="@item.Id" data-reveal-id="Update" class="UpdateBtn"><i class="glyphicon glyphicon-edit"></i</a>  
                          <a href="#" id="@item.Id" data-reveal-id="Delete" class="DeleteBtn"><i class="glyphicon glyphicon-remove"></i></a>  
                            </td>  
                         </tr>  
                        }  
                    </tbody>  
                </table>  
            </div>  
        </div>  
    </div>  
    <div id="Update" class="reveal-modal"></div>  
    <div id="Delete" class="reveal-modal"></div>  
    <a href="#" id="Create" class="reveal-modal"></a>  


Add the following  jQuery in the script section at the bottom of the index view to load other views.
    @section Scripts{  
        <script type="text/javascript">  
            $(document).ready(function () {  
                $('.UpdateBtn').click(function () {  
                    var url = '@Url.Action("Update","Home")';  
                    url = url + "?Id=" + this.id;  
                    $('#Update').load(url);  
                });  
            });  
        </script>  
        <script type="text/javascript">  
            $(document).ready(function () {  
                $('.DeleteBtn').click(function () {  
                    var url = '@Url.Action("Delete","Home")';  
                    url = url + "?Id=" + this.id;  
                    $('#Delete').load(url);  
                });  
            });  
        </script>  
        <script type="text/javascript">  
            $(document).ready(function () {  
                $('.CreateBtn').click(function () {  
                    var url = '@Url.Action("Create","Home")';  
                    $('#Create').load(url);  
                });  
            });  
        </script>  
    }  


Step 14
Now, run the application.

Update view

Delete view

Thank you so much for your reading. I hope the article is useful for all the readers. If you have any complaint or suggestion about the code or the article, please let me know. Don't forget to leave your opinion in the comments section bellow. 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: DataTables Grid Integration with ASP.NET MVC

clock June 22, 2023 09:11 by author Peter

What exactly is DataTables?
DataTables is a jQuery Javascript library plug-in. It is a highly flexible tool that adds advanced interaction controls to any HTML table. It is founded on the principles of progressive enhancement.


Let's begin with the database section.

Database Part

I've created a database called "Northwind" that contains a "Customers" entity.

Next, we are going to create an ASP.NET MVC5 Web application.

Creating ASP.NET MVC5 Web Application
Open New Visual Studio 2015 IDE.


After opening IDE just, next we are going to create MVC project for doing that just click File - inside that New - Project.

After choosing a project, a new dialog will pop up with the name “New Project”. In that, we are going to choose Visual C# Project Templates - Web - ASP.NET Web Application. Then, we are going to name the project as “DemoDatatables”.

After naming the project we are going click on OK button to create a project.
A new dialog will pop up for choosing templates for Creating “ASP.NET Web Application;” in that template, we are going to Create MVC application. That's why we are going to choose “MVC template” and next click on OK button to create a project.

After clicking on OK button it will start to create a project.

Project Structure

After creating project next, we are going to create Model.

Creating Customer Model
We are going to add Customer Model to the Models folder.

After adding Action Method now let add View with name “ShowGrid”.


Adding DataTables Grid Scripts and Css on ShowGrid View

In first step we are going to add Script and Css reference.
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
    <link href="~/Content/bootstrap.css" rel="stylesheet" />  
      
    <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
    <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />  
      
    <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>  
    <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  

After adding Script and CSS reference next we are going to add DataTables Markup.

Adding DataTables Markup
It is simple Html Table in that we are going to add columns headers (“<th>”) with all the columns names which we want to display on the grid.

After adding Markup next, we are going to add DataTables function to Create DataTables.

    <div class="container">  
            <br />  
            <div style="width:90%; margin:0 auto;">  
                <table id="demoGrid" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">  
                    <thead>  
                  <tr>  
                    <th>CustomerID</th>  
                    <th>CompanyName</th>      
                    <th>ContactName</th>  
                    <th>ContactTitle</th>  
                    <th>City</th>  
                    <th>PostalCode</th>  
                    <th>Country</th>  
                    <th>Phone</th>  
                    <th>Edit</th>  
                    <th>Delete</th>  
                </tr>  
                    </thead>  
                </table>  
            </div>  
        </div>  


Adding DataTables Function to create DataTables
Code Snippet
    <script>  
      
        $('#demoGrid').dataTable({  
        });  
    </script>  

DataTables Options

  • Processing - Enable or disable the display of a 'processing' indicator when the table is being processed (e.g. a sort).
  • server Side - Server-side processing - where filtering, paging, and sorting calculations are all performed by a server.
  • Filter - this option is used for enabling and disabling of search box
  • orderMulti - When ordering is enabled (ordering), by default DataTables allows users to sort multiple columns by shift-clicking upon the header cell for each column. Although this can be quite useful for users, it can also increase the complexity of the order, potentiality increasing the processing time of ordering the data. Therefore, this option is provided to allow this shift-click multiple column abilities
  • Ajax - Ajax request is made to get data to DataTables.
  • columnDefs - Set column definition initialisation properties.
  • Columns - Set column specific initialisation properties.


After completing with an understanding of options or properties next we are going to set it.

We are going to set “processing” option to true to display processing bar, after that, we are going to set the “serverSide” option to true because we are going to do paging and filtering at serverSide.

Next options after “serverSide” option are “filter.” We are going to use the search box; that's why we have set this property to true, “orderMulti” is also set to false because we do not want to sort multiple columns at once.

DataTables Options snapshot

Ajax Option
And the main option is Ajax which we are going to use for calling an Action Method for getting data to bind DataTables Grid the data is in Json format. For that we are going to pass URL: -"/Demo/LoadData”, this request is Post request. And data type we are going to set as Json.

We are going to call LoadData Action Method which is under Demo Controller which I will explain in upcoming steps.

columnDefs Option
After setting Ajax we have a “columnDefs” option which I have used for hiding Primary key of the table (“CustomerID”) and which should also be not searchable.

columns Option
Finally, the second to last option is columns which are used for initialization of DataTables grid. Add that property which you need to render on the grid, which must be defined in this columns option.

Finally, on click of the delete button, we can call a custom function to delete data as I have created “DeleteData” function.
Complete code Snippet of ShowGrid View
    @{  
        Layout = null;  
    }  
      
    <!DOCTYPE html>  
    <html>  
    <head>  
        <meta name="viewport" content="width=device-width" />  
        <title>ShowGrid</title>  
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
        <link href="~/Content/bootstrap.css" rel="stylesheet" />  
      
        <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
        <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />  
      
        <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>  
        <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  
      
        <script>  
            $(document).ready(function () {  
                $("#demoGrid").DataTable({  
      
                    "processing": true, // for show progress bar  
                    "serverSide": true, // for process server side  
                    "filter": true, // this is for disable filter (search box)  
                    "orderMulti": false, // for disable multiple column at once  
                    "pageLength": 5,  
      
                    "ajax": {  
                        "url": "/Demo/LoadData",  
                        "type": "POST",  
                        "datatype": "json"  
                    },  
      
                    "columnDefs":  
                    [{  
                        "targets": [0],  
                        "visible": false,  
                        "searchable": false  
                    },  
                    {  
                        "targets": [7],  
                        "searchable": false,  
                        "orderable": false  
                    },  
                    {  
                        "targets": [8],  
                        "searchable": false,  
                        "orderable": false  
                    },  
                    {  
                        "targets": [9],  
                        "searchable": false,  
                        "orderable": false  
                    }],  
      
                    "columns": [  
                          { "data": "CustomerID", "name": "CustomerID", "autoWidth": true },  
                          { "data": "CompanyName", "name": "CompanyName", "autoWidth": true },  
                          { "data": "ContactName", "title": "ContactName", "name": "ContactName", "autoWidth": true },  
                          { "data": "ContactTitle", "name": "ContactTitle", "autoWidth": true },  
                          { "data": "City", "name": "City", "autoWidth": true },  
                          { "data": "PostalCode", "name": "PostalCode", "autoWidth": true },  
                          { "data": "Country", "name": "Country", "autoWidth": true },  
                          { "data": "Phone", "name": "Phone", "title": "Status", "autoWidth": true },  
                          {  
                              "render": function (data, type, full, meta)  
                              { return '<a class="btn btn-info" href="/Demo/Edit/' + full.CustomerID + '">Edit</a>'; }  
                          },  
                           {  
                               data: null, render: function (data, type, row) {  
                                   return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";  
                               }  
                           },  
      
                    ]  
      
                });  
            });  
        </script>  
      
    </head>  
    <body>  
        <div class="container">  
            <br />  
            <div style="width:90%; margin:0 auto;">  
                <table id="demoGrid" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">  
                    <thead>  
                        <tr>  
                            <th>CustomerID</th>  
                            <th>CompanyName</th>  
                            <th>ContactName</th>  
                            <th>ContactTitle</th>  
                            <th>City</th>  
                            <th>PostalCode</th>  
                            <th>Country</th>  
                            <th>Phone</th>  
                            <th>Edit</th>  
                            <th>Delete</th>  
                        </tr>  
                    </thead>  
                </table>  
            </div>  
        </div>  
    </body>  
    </html>  

After completing with initialization of DataTables grid next we are going to create LoadData Action Method.

Adding LoadData Action Method to Demo Controller
Here we are going to Add Action Method with name LoadData. In this action method, we are going to get all Customer records from the database to display and on the basis of the parameter we are going sort data, and do paging with data.

We are doing paging and filtering of data on the server side; that why we are using IQueryable which will execute queries with filters on the server side.

Render buttons in Columns
At last, we need to render button in the grid for editing data and deleting data.


    @{  
        Layout = null;  
    }  
      
    <!DOCTYPE html>  
    <html>  
    <head>  
        <meta name="viewport" content="width=device-width" />  
        <title>ShowGrid</title>  
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
        <link href="~/Content/bootstrap.css" rel="stylesheet" />  
      
        <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
        <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />  
      
        <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>  
        <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  
      
        <script>  
            $(document).ready(function () {  
                $("#demoGrid").DataTable({  
      
                    "processing": true, // for show progress bar  
                    "serverSide": true, // for process server side  
                    "filter": true, // this is for disable filter (search box)  
                    "orderMulti": false, // for disable multiple column at once  
                    "pageLength": 5,  
      
                    "ajax": {  
                        "url": "/Demo/LoadData",  
                        "type": "POST",  
                        "datatype": "json"  
                    },  
      
                    "columnDefs":  
                    [{  
                        "targets": [0],  
                        "visible": false,  
                        "searchable": false  
                    },  
                    {  
                        "targets": [7],  
                        "searchable": false,  
                        "orderable": false  
                    },  
                    {  
                        "targets": [8],  
                        "searchable": false,  
                        "orderable": false  
                    },  
                    {  
                        "targets": [9],  
                        "searchable": false,  
                        "orderable": false  
                    }],  
      
                    "columns": [  
                          { "data": "CustomerID", "name": "CustomerID", "autoWidth": true },  
                          { "data": "CompanyName", "name": "CompanyName", "autoWidth": true },  
                          { "data": "ContactName", "title": "ContactName", "name": "ContactName", "autoWidth": true },  
                          { "data": "ContactTitle", "name": "ContactTitle", "autoWidth": true },  
                          { "data": "City", "name": "City", "autoWidth": true },  
                          { "data": "PostalCode", "name": "PostalCode", "autoWidth": true },  
                          { "data": "Country", "name": "Country", "autoWidth": true },  
                          { "data": "Phone", "name": "Phone", "title": "Status", "autoWidth": true },  
                          {  
                              "render": function (data, type, full, meta)  
                              { return '<a class="btn btn-info" href="/Demo/Edit/' + full.CustomerID + '">Edit</a>'; }  
                          },  
                           {  
                               data: null, render: function (data, type, row) {  
                                   return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";  
                               }  
                           },  
      
                    ]  
      
                });  
            });  
        </script>  
      
    </head>  
    <body>  
        <div class="container">  
            <br />  
            <div style="width:90%; margin:0 auto;">  
                <table id="demoGrid" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">  
                    <thead>  
                        <tr>  
                            <th>CustomerID</th>  
                            <th>CompanyName</th>  
                            <th>ContactName</th>  
                            <th>ContactTitle</th>  
                            <th>City</th>  
                            <th>PostalCode</th>  
                            <th>Country</th>  
                            <th>Phone</th>  
                            <th>Edit</th>  
                            <th>Delete</th>  
                        </tr>  
                    </thead>  
                </table>  
            </div>  
        </div>  
    </body>  
    </html>  

After completing with initialization of DataTables grid next we are going to create LoadData Action Method.

Adding LoadData Action Method to Demo Controller
Here we are going to Add Action Method with name LoadData. In this action method, we are going to get all Customer records from the database to display and on the basis of the parameter we are going sort data, and do paging with data.

We are doing paging and filtering of data on the server side; that why we are using IQueryable which will execute queries with filters on the server side.

For using OrderBy in the query we need to install System.Linq.Dynamic package from NuGet packages.

Snapshot while adding System.Linq.Dynamic package from NuGet packages

After adding the package, next, we see the complete code snippet and how to get data and do paging and filtering with it.

Complete code Snippet of LoadData Action Method
All processes are step by step with comments; so it's easy to understand.

All Request.Form.GetValues parameters value will get populated when AJAX post method gets called on a load of if you do paging or sorting and search.
Code Snippet
    public ActionResult LoadData()  
    {  
        try  
        {  
            var draw = Request.Form.GetValues("draw").FirstOrDefault();  
            var start = Request.Form.GetValues("start").FirstOrDefault();  
            var length = Request.Form.GetValues("length").FirstOrDefault();  
            var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();  
            var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();  
            var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();  
      
      
            //Paging Size (10,20,50,100)    
            int pageSize = length != null ? Convert.ToInt32(length) : 0;  
            int skip = start != null ? Convert.ToInt32(start) : 0;  
            int recordsTotal = 0;  
      
            // Getting all Customer data    
            var customerData = (from tempcustomer in _context.Customers  
                                select tempcustomer);  
      
            //Sorting    
            if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))  
            {  
                customerData = customerData.OrderBy(sortColumn + " " + sortColumnDir);  
            }  
            //Search    
            if (!string.IsNullOrEmpty(searchValue))  
            {  
                customerData = customerData.Where(m => m.CompanyName == searchValue);  
            }  
      
            //total number of rows count     
            recordsTotal = customerData.Count();  
            //Paging     
            var data = customerData.Skip(skip).Take(pageSize).ToList();  
            //Returning Json Data    
            return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });  
      
        }  
        catch (Exception)  
        {  
            throw;  
        }  
      
    }  


Complete code Snippet of DemoController
    using DemoDatatables.Models;  
    using System;  
    using System.Linq;  
    using System.Web.Mvc;  
    using System.Linq.Dynamic;  
    using System.Data.Entity;  
      
    namespace DemoDatatables.Controllers  
    {  
        public class DemoController : Controller  
        {  
            // GET: Demo  
            public ActionResult ShowGrid()  
            {  
                return View();  
            }  
      
            public ActionResult LoadData()  
            {  
                try  
                {  
                    //Creating instance of DatabaseContext class  
                    using (DatabaseContext _context = new DatabaseContext())  
                    {  
                        var draw = Request.Form.GetValues("draw").FirstOrDefault();  
                        var start = Request.Form.GetValues("start").FirstOrDefault();  
                        var length = Request.Form.GetValues("length").FirstOrDefault();  
                        var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();  
                        var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();  
                        var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();  
      
      
                        //Paging Size (10,20,50,100)    
                        int pageSize = length != null ? Convert.ToInt32(length) : 0;  
                        int skip = start != null ? Convert.ToInt32(start) : 0;  
                        int recordsTotal = 0;  
      
                        // Getting all Customer data    
                        var customerData = (from tempcustomer in _context.Customers  
                                            select tempcustomer);  
      
                        //Sorting    
                        if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))  
                        {  
                            customerData = customerData.OrderBy(sortColumn + " " + sortColumnDir);  
                        }  
                        //Search    
                        if (!string.IsNullOrEmpty(searchValue))  
                        {  
                            customerData = customerData.Where(m => m.CompanyName == searchValue);  
                        }  
      
                        //total number of rows count     
                        recordsTotal = customerData.Count();  
                        //Paging     
                        var data = customerData.Skip(skip).Take(pageSize).ToList();  
                        //Returning Json Data    
                        return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });  
                    }  
                }  
                catch (Exception)  
                {  
                    throw;  
                }  
      
            }  
         
        }  
    }  

Save the entire Source code and run the application.

Run Application
To access the application, enter URL - http://localhost:#####/demo/showgrid .

“#####” is localhost port number.

Real-time Debugging Snapshot
In this section, you can see what values are populated when post method gets called.

Search with DataTables grid
In this section we have implemented a search for only Companyname column, if you want to add another column just use or condition (“||”) with it.


Adding more columns to search

Debugging View of Search

After completing with search Implementation next we are going to work on Edit Button of DataTables Grid.

Edit Event in DataTables grid
In this section first we are going add Edit Action Method in Demo Controller which will handle edit request and it will take Customer ID as input from which we are going to get details of that customer.

Code Snippet of Edit Action Method
    [HttpGet]  
    public ActionResult Edit(int? ID)  
    {     
        try  
        {  
            using (DatabaseContext _context = new DatabaseContext())  
            {  
                var Customer = (from customer in _context.Customers  
                                where customer.CustomerID == ID  
                                select customer).FirstOrDefault();  
      
                return View(Customer);  
            }  
        }  
        catch (Exception)  
        {  
            throw;  
        }     
    }  


After having a look on Edit action method next let’s see how to render Edit link (button).

Below is syntax for rendering Edit button

Finally, you can see Edit View.

After completing with Edit part next we are going to have a look at delete part.

Delete Event in DataTables grid
In this section first we are going add DeleteCustomer Action Method in DemoController which will handle delete request and it will take Customer ID (“ID”) as input from which we are going to delete customer data.

Code Snippet of DeleteCustomer
    [HttpPost]  
    public JsonResult DeleteCustomer(int? ID)  
    {  
        using (DatabaseContext _context = new DatabaseContext())  
        {  
            var customer = _context.Customers.Find(ID);  
            if (ID == null)  
                return Json(data: "Not Deleted", behavior: JsonRequestBehavior.AllowGet);  
            _context.Customers.Remove(customer);  
            _context.SaveChanges();  
      
            return Json(data: "Deleted", behavior: JsonRequestBehavior.AllowGet);  
        }  
    }  


After having a look on DeleteCustomer action method next let’s see how to render delete link (button).

Below is syntax for rendering Delete button

Now you can see that we are generating simple href button and on that button, we have added an onclick event to call DeleteData function which we have not created yet, so  let’s create DeleteData function.

Code Snippet
In this part when user clicks on Delete button DeleteData function will get called and first thing it will show is confirmation alert ("Are you sure you want to delete ...?") if you click on ok (confirm) button then it will call Delete function. This function takes CustomerID as input, next we are generating URL of DeleteCustomer Action Method and passing it as ajax post request and along with it we are passing Customer ID as parameter.

If data is deleted, then we are going to get “Deleted” as a response from Deletecustomer Action Method, finally, we show alert to the user and reload grid.
    <script>  
      
        function DeleteData(CustomerID) {  
            if (confirm("Are you sure you want to delete ...?")) {  
                Delete(CustomerID);  
            }  
            else {  
                return false;  
            }  
        }  
      
      
        function Delete(CustomerID) {  
            var url = '@Url.Content("~/")' + "Demo/DeleteCustomer";  
            $.post(url, { ID: CustomerID }, function (data) {  
                if (data == "Deleted") {  
                    alert("Delete Customer !");  
                    oTable = $('#demoGrid').DataTable();  
                    oTable.draw();  
                }  
                else {  
                    alert("Something Went Wrong!");  
                }  
            });  
        }  
    </script>  

Debugging View while deleting customer

Finally, we have learned how to use jQuery DataTables Grid with ASP.NET CORE MVC. I hope you enjoyed the article.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Implement Cascading Dropdown In ASP.NET Core MVC Application Using InMemory DB

clock May 17, 2023 10:15 by author Peter

Today, this article will discuss how we can design or develop any dependent or cascading dropdown control in Asp.net Core MVC Application. While developing any application using any language, sometimes we must define dropdown control that populates data from the backend part, i.e., from the database section. So, control directly fetches data from the database by using APIs and displays it in the dropdown control. But, sometimes, we need to implement the dependent dropdown control. It means the value of the dependent dropdown control depends on another. So, as per the selected value of the first dropdown control, we need to pass that value to the database side with the help of a parameter, and then as per that value, it will return the corresponding values to bind the second control. In this article, we will demonstrate this function with the help of the Asp.Net Core MVC Application.


Pre-Requisites
We must create a sample application using Asp.Net Core to demonstrate the functionality. For that purpose, we will use the .Net 7.0 framework. So, we need the below tools as a pre-requisite.
    Visual Studio 2022 Community Edition / Visual Studio Code
    .Net 7.0 SDK (only required if we use Visual Studio Code as Code Editor).

Also, we are not using any database tools for the database-related part. For the time-saving part, we are using the In-Memory database features of the Asp.Net Core application. We must use database tools like SQL, Oracle, MySQL, etc. In that case, we can need to replace the In-Memory database connection part with the actual database connection details.

In this example, we will use two models: Category and Product. Every product information is tagged with an existing category. So, finally, in the view part, once we select any Category value from the dropdown, it will populate related product items accordingly.
Steps to Develop Cascading Dropdown in Asp.Net Core MVC

Step 1
Open Visual Studio 2022 and click on Create New Project with the template "Asp.Net Core Web App (Model-View-Controller)."

Step 2
Then click on the Next Button and provide the Project Name.

Step 3
Then click on the Next Button and select .Net 7.0 as the Framework version. (If anyone is using VS 2019, then also select .Net 5.0 or .Net 6.0)

Step 6
Select the Model folder, create a new class file called Category.cs, and add the code below.
public class Category {
    public int Id {
        get;
        set;
    }
    public string Name {
        get;
        set;
    }
    public virtual List < Product > Products {
        get;
        set;
    }
}

Step 7
Again, add another new file called Product.cs and add the below code –
public class Product {
    public int Id {
        get;
        set;
    }
    public string Code {
        get;
        set;
    }
    [Required]
    public string Name {
        get;
        set;
    }
    [MaxLength(255)]
    public string ? Description {
        get;
        set;
    }
    public decimal Price {
        get;
        set;
    }
    public bool IsAvailable {
        get;
        set;
    }
    public int CategoryId {
        get;
        set;
    }
    [JsonIgnore]
    public virtual Category Category {
        get;
        set;
    }
}


Step 8

Now, we need to create the DBContext File. So, we need to add a new file called InMemoryDBContext.cs file and the below code in that file.
public class InMemoryDBContext: DbContext {
    public InMemoryDBContext(DbContextOptions < InMemoryDBContext > options): base(options) {}
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity < Category > ().HasMany(c => c.Products).WithOne(a => a.Category).HasForeignKey(a => a.CategoryId);
        modelBuilder.Seed();
    }
    public DbSet < Product > Products {
        get;
        set;
    }
    public DbSet < Category > Categories {
        get;
        set;
    }
}

Step 9
In the above code, we invoke the Seed() of the ModelBuilder. This method is responsible for initiating the base data related to the Category and Product. For that purpose, we have created a static call called ModelBuilderExtensions and implemented the Seed() method in that class with some sample data. So, we call the Category or Product list from the View Part; it populates the data from this list.

Step 10
After that, we need to open the Program.cs File and add the below code in that File.
builder.Services.AddDbContext<InMemoryDBContext>(options => options.UseInMemoryDatabase("Shop"));
builder.Services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
    // options.SuppressModelStateInvalidFilter = true;
  }
);


Step 11

Now, we can perform the scaffold function of the Asp.Net Core MVC Application to generate the entire View & Controller layer related to the Category and Products. Once the scaffold files are created, we can execute the application and display just like below for both category and product parts.


 

Step 12
Now, open the Index.cshtml view under the Home folder. There add the below code to populate two different dropdown control related to the Category and Product list.
@{
    ViewData["Title"] = "Home Page";
    var baseurl = ViewBag.BaseUrl;
}

<div class="text-center">
    <h2>Cascading Dropdown Demo</h2>

    <div class="row form-group">
        <div class="col-md-2">
            <label asp-for="CategoryId" class="control-label"></label>
        </div>
        <div class="col-md-4">
            <select asp-for="CategoryId" class="form-control"
                    asp-items="ViewBag.CategoryData"
                    id="CategoryId"></select>
        </div>
        <div class="col-md-2">
            <label asp-for="ProductId" class="control-label"></label>
        </div>
        <div class="col-md-4">
            <select asp-for="ProductId" class="form-control" asp-items="ViewBag.ProductData" id="ddlProductId"></select>
        </div>
    </div>
</div>


Step 13
Now, open the HomeController.cs file under the controller folder and add the below code in the Index Action method. This code will fetch the Category and the Product list and return it as a view bag object. Initially, it does not produce any list value of the Product, as it will only populate if we pass any category id value to filter the product list.
public class HomeController: Controller {
    private readonly ILogger < HomeController > _logger;
    private readonly InMemoryDBContext _context;
    public HomeController(ILogger < HomeController > logger, InMemoryDBContext context) {
        _logger = logger;
        _context = context;
        _context.Database.EnsureCreated();
    }
    public IActionResult Index() {
        var _categories = _context.Categories.ToList();
        var _products = new List < Product > ();
        _categories.Add(new Category() {
            Id = 0, Name = "--Select Category--"
        });
        _products.Add(new Product() {
            Id = 0, Name = "--Select Product--"
        });
        ViewData["CategoryData"] = new SelectList(_categories.OrderBy(s => s.Id), "Id", "Name");
        ViewData["ProductData"] = new SelectList(_products.OrderBy(s => s.Id), "Id", "Name");
        string host = $ "{Request.Scheme}://{Request.Host}{Request.PathBase}/";
        ViewData["BaseUrl"] = host;
        return View();
    }
    public IActionResult Privacy() {
            return View();
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error() {
        return View(new ErrorViewModel {
            RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
        });
    }
}


Step 14
Now, we can run the application and check that the category dropdown already binds with the existing category data. But, the product dropdown does secure any data.

Step 15
We need to add a new action method to return the filtered product list as per the selected category id. This method accepts one input value called categoryId from the View part, and as per that categoryId, it will filter the product list and return the data in a JSON format. For that, open the ProductController.cs file and add the code below.
[HttpPost, ActionName("GetProductsByCategoryId")]
public JsonResult GetProductsByCategoryId(string categoryId) {
    int catId;
    List < Product > productLists = new List < Product > ();
    if (!string.IsNullOrEmpty(categoryId)) {
        catId = Convert.ToInt32(categoryId);
        productLists = _context.Products.Where(s => s.CategoryId.Equals(catId)).ToList();
    }
    return Json(productLists);
}

Step 16
We must consume the above action method from the view to retrieve the JSON data and bind it with the product dropdown. For that, we will take the help of JQuery code. Now, return to the Index.cshtml file under the home folder and add the below code there under script sections –
@section scripts
    {
    <script type="text/javascript">
        $(document).ready(function () {
            var a = 0;
        });
        function loadProduct(obj) {
            var value = obj.value;
            var url = "@baseurl";
            $.post(url + "Products/GetProductsByCategoryId", { categoryId: value }, function (data) {
                debugger;
                PopulateDropDown("#ddlProductId", data);
            });
        }
        function PopulateDropDown(dropDownId, list, selectedId) {
            $(dropDownId).empty();
            $(dropDownId).append("<option>--Please Product--</option>")
            $.each(list, function (index, row) {
                $(dropDownId).append("<option value='" + row.id + "'>" + row.name + "</option>")
            });
        }
    </script>
}


Step 17    
Now, invoke the loadProduct() method from the HTML part related to the Product dropdown. For that, change the code related to the product dropdown as below –
<select asp-for="CategoryId" class="form-control"
                   asp-items="ViewBag.CategoryData"
                   id="CategoryId" onchange="loadProduct(this)"></select>

Step 18
Now, run the application, select any category from the dropdown, and check related products populated within the product dropdown.


This article discusses cascading dropdown generation using the Asp.Net Core MVC application. Also, we discussed the steps related to implementing the In-Memory database concept. Any suggestions, feedback, or queries related to this article are appreciated.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Three Different Ways to Upload a File in ASP.NET MVC

clock May 5, 2023 08:41 by author Peter

There are a few things that all web applications have in common. File Upload is one of the most common things that all web applications have. This is used to move data, upload large amounts of data, upload pictures, videos, etc.


I've mostly seen three ways to share a file while working on different web apps and products, especially in ASP.NET MVC. We will look at it in depth.

1. File Control with Html.BeginForm
When we submit the form, we can post our selected file to the server and read it. Below is the code to bind the File control
@Html.TextBoxFor(model =>
       model.DocumentFile, new {
                type = "file",
                @id = "documentFile"

})


And the type of DocumentFile property is as below.
public HttpPostedFileBase DocumentFile { get; set; }

To save this file, we created one folder and added the path of the folder in the config. We are accessing the folder location as below
var path = ConfigurationManager.AppSettings["CustomerDocuments"].ToString();


Now we need to save the file in the folder and insert the path of the file in the database

if (objGroup.GSTDocumentFile != null)
{
     using (Stream inputStream = objGroup.GSTDocumentFile.InputStream)
     {
         byte[] data;
         using (MemoryStream ms = new MemoryStream())
         {
             inputStream.CopyTo(ms);
             data = ms.ToArray();
         }
         System.IO.File.WriteAllBytes(Path.Combine(ClientFolder, objGroup.GSTDocumentFile.FileName), data);
     }
        objGroup.Document = objGroup.DocumentFile.FileName;
}


2. File upload using AJAX - Base64 as a parameter
When we select a file using file upload on the browser, we need to fire an event to capture the file like below
document.getElementById("uploadfile").addEventListener('change', handleFileSelect, false);

Using this event listener, we execute the function on selection of file and capture the file as below
function handleFileSelect(evt) {

     const id = evt.currentTarget.id;
     const f = evt.target.files[0];
     const Name = evt.target.files[0].name;
     const reader = new FileReader();

     reader.onload = (function(theFile) {

          return function(e) {

               const binaryData = e.target.result;
               const base64String = window.btoa(binaryData);

               $("#uploadDocBase64").val(base64String);
               $("#uploadFileName").val(Name);

          };

     })(f);

     reader.readAsBinaryString(f);

}


Here we capture the  file as well as the file name, and using AJAX, we can send this file to the server
try {

  const response = await fetch('@Url.Action("FileUpload", "Upload")', {
    method: 'POST',
    body: JSON.stringify({ fileStr: $("#uploadDocBase64").val() }),
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }
  });

  const result = await response.json();

  alert('Success');

} catch (error) {

  alert('Failure');
  console.error(error);

}


System.IO.File.WriteAllBytes(path, Convert.FromBase64String(Convert.ToString(fileStr)));

3. File Upload using Fetch with FileData

There is an issue with option no 2. Big files are not getting uploaded as it is going in the parameter. To overcome this, we can add all the parameters and files in fileData and upload a file.
try {

  const fileData = new FormData();

  fileData.append("File", $("#uploadDocBase64").val());

  const response = await fetch('@Url.Action("UpdateStatusAndDiscussion", "Discussion")', {
    method: 'POST',
    body: fileData,
  });

  if (response.ok) {
    alert("Success");
  } else {
    alert("Failure");
  }

} catch (error) {
  console.error(error);
}


Now you can capture the file in the controller
byte[] imageBytes = Convert.FromBase64String(File);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
path = HttpContext.Current.Server.MapPath("~/FileUpload/" + _GroupName + "/" + DoneFileName);
FileStream fileNew = new FileStream(path, FileMode.Create, FileAccess.Write);
ms.WriteTo(fileNew);
fileNew.Close();
ms.Close();


These are the ways to upload files to the server using ASP.NET MVC.




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