European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Create Dynamic Models with a Database in C#.NET 8 MVC

clock April 17, 2024 07:37 by author Peter

In order to fill database tables with data, models must be created. However, what happens if you have to generate models dynamically rather than building your model with classes and properties? In this scenario, you will have to develop code that uses the table schema to create the models at runtime. In this post, we'll build a dynamic model generator that can produce models from your database table schema automatically using C#.NET 8 MVC.

How does dynamic model generation work?

Developers frequently spend a great deal of effort building models that match the structure of their database tables when using standard C#.NET MVC development. This procedure, which can be laborious, prone to errors, and not very scalable, particularly for applications with big databases, entails defining characteristics for each column in the table. The process of dynamically generating models at runtime based on database table schema is known as dynamic model generation. We can automate this process by querying the database for each table's structure and dynamically creating the associated C# classes, saving us the trouble of constructing model classes by hand for each table.

C#.NET 8 Project for creating dynamic models
You can skip the project creation section if you have previously created the project because I will be going over every step from beginning to end. Let's now create a project to see how this is accomplished.

Step 1: Needs

Since I'll be working with.NET 8, it needs to be installed (if you're using a different version, that depends on your needs).

Step 2. Setting up the Project

  • In the Visual Studio, click 'Create a new project' and click 'Next.'
  • In templates, select 'ASP.NET Core Web App (Model-View-Controller)' and click 'Next'.
  • In the 'Configure your new project' window, name your project, here I have named it 'DynamicModelGenerator' and click 'Next'.
  • In the Additional Information window, in Framework, choose '.NET 8' and click 'Create'.
  • Now, the project is created and the project structure looks like the below image.

Install packages in step three
Let's now install the project-related packages. We will utilize Entity for database operations in our project. Let's install it now.

  • Choose 'Manage NuGet Packages' after clicking 'Project'.
  • Type 'EntityFramework' into the 'Browse' search field.
  • Click 'Install' after selecting it.
  • There will be a pop-up window; click "I accept."
  • Now that Entity Framework is installed, it seems as follows.

Configure the connection string in step four
Let's now update the appsettings.json file with a connection string. In accordance with your database, change the Server, Database, User ID, and Password.

"ConnectionStrings": {
  "DefaultConnection": "Server=******;Database=******;user id=******;Password=******;MultipleActiveResultSets=true;Encrypt=False;"
},

Create Index View

In the HomeController, we have an Index method, by default, it has some boilerplate code written. Let's change it according to our requirements. Here, I am changing some basic code that is needed for our implementation.
In Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}

<div>
    <h2>Dynamic Model Generator</h2>
    <p>Generate dynamic models and use them in your application.</p>
    <p>Click <a href="/get-database-tables">here</a> to get all the tables present in your database.</p>
</div>


In the above, I have added a title to the page, a heading in the home page some info in <p> tag and <a> tag to provide a link on whose click, and a method having route 'get-database-tables' will be called. The view will look like below.

Make a Controller for ModelGenerator
It is best practice to divide your code into distinct controllers based on your needs. So, make a controller and give it a suitable name. 'ModelGeneratorController' is the name I gave it. This is how your controller will appear below.

using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;

public class ModelGeneratorController : Controller
{
    //empty controller
}


In this controller, let's add a constructor and a read-only property.
private readonly string _connectionString;

public ModelGeneratorController(IConfiguration configuration)
{
    _connectionString = configuration.GetConnectionString("DefaultConnection");
}


In the above, I added a private read-only string named _connectionString to store the database connection string. Then, I created a constructor and in that, I assigned the connection string stored in our appsettings.json file to the _connectionString property.

Create a method to get all database tables
Now, let's create a method to get all the tables present in our database.

[HttpGet]
[Route("get-database-tables")]
public IActionResult GetDatabaseTables()
{
    var tableNames = new List<string>();

    using (var connection = new SqlConnection(_connectionString))
    {
        connection.Open();
        var command = connection.CreateCommand();
        command.CommandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        var reader = command.ExecuteReader();

        while (reader.Read())
        {
            tableNames.Add(reader.GetString(0));
        }

        reader.Close();
    }

    return View(tableNames);
}

In the above code I created a method named GetDatabaseTables(). made it HTTP GET to handle the GET request, method and gave it the route 'get-database-tables', which we used in index.cshtml page.

In this method, I created a variable tableNames, a list of string values, which will be used to store the list of tables present in the database. In the next line, I created a connection with SQL Server and then opened the connection. In the next line, I created a SQL command (SqlCommand) to execute a SQL query against the database. The query selects table names from the INFORMATION_SCHEMA.TABLES view where the TABLE_TYPE is 'BASE TABLE'.

This ensures that only base tables (not views or system tables) are included in the result. In the next line, I executed the command using ExecuteReader() and iterated over the results using a while loop. For each row in the result set, it reads the value of the first column (table name) using the reader.GetString(0) and add it to the tableNames list. After reading all the data, we closed the data reader and the database connection to release resources. At last, I passed the table names to the View().

Create a view to show the tables present in the database

To create a view, right-click on GetDatabaseTables() method, click, 'Add View', and name the view, I named it 'GetDatabaseTables.cshtml'. Your view file is created
In GetDatabaseTables.cshtml
@model List<string>
@{
    ViewData["Title"] = "Database Tables";
}
<!DOCTYPE html>
<html>
<head>
    <title>@ViewData["Title"]</title>
    <style>
        table {
            width: 40%;
            border-collapse: collapse;
        }

        th, td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        tr:hover {
            background-color: #ddd;
        }

        a {
            text-decoration: none;
            color: blue;
        }

            a:hover {
                text-decoration: underline;
            }
    </style>
</head>
<body>
    <div>
        <h1>Database Tables</h1>
        <table>
            <thead>
                <tr>
                    <th>Table Name</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var tableName in Model)
                {
                    <tr>
                        <td>@tableName</td>
                        <td><a href="@Url.Action("CreateDynamicModel", "ModelGenerator", new { tableName = tableName })">Create Dynamic Model</a></td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</body>
</html>


In the above code, I added a directive that specifies the type of model that this view expects. In our case, it expects a List<string>, which means it will receive a list of strings from the controller. Then, added a title to the page. In the body, I created a <div>, and inside that <div>, added a for each loop to iterate over the list of table names and display them in a tabular format with some CSS styling. This will look like below.


Create a method to create a dynamic model
[HttpGet]
[Route("create-dynamic-model")]
public string CreateDynamicModel(string tableName)
{
    StringBuilder classDefinition = new();

    classDefinition.AppendLine($"public class {tableName}Model");
    classDefinition.AppendLine("{");

    List<string> propertyDeclarations = GetPropertyDeclarationsForTable(tableName);

    foreach (var propertyDeclaration in propertyDeclarations)
    {
        classDefinition.AppendLine($"    {propertyDeclaration}");
    }

    classDefinition.AppendLine("}");

    return classDefinition.ToString();
}

In the above method, I created a StringBuilder object and then started constructing a model class by getting property declarations for the table. and inside a for each loop, generated all property declarations. Once the class construction is completed, I returned the constructed class to the view.

Step 10. Create GetPropertyDeclarationsForTable() method

In the above method, we used GetPropertyDeclarationsForTable(), now let's create the method.
private List<string> GetPropertyDeclarationsForTable(string tableName)
{
    List<string> propertyDeclarations = [];

    using (var oldConnection = new SqlConnection(_connectionString))
    {
        oldConnection.Open();

        string sql = $"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{tableName}'";
        using var cmd = new SqlCommand(sql, oldConnection);
        using SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            string columnName = reader["COLUMN_NAME"].ToString();
            string dataType = reader["DATA_TYPE"].ToString();
            bool isNullable = reader["IS_NULLABLE"].ToString() == "YES";

            string propertyDeclaration = $"public {GetCSharpType(dataType, isNullable)} {columnName} {{ get; set; }}";
            propertyDeclarations.Add(propertyDeclaration);
        }

        oldConnection.Close();
    }

    return propertyDeclarations;
}


In the above method, I created a list of strings. In the next line, I established the connection and got the data using an SQL connection. In next line, in a while loop, i got the information about the columns and constructed property declaration, using that information. Next, added that declaration to the string list. After closing the connection, I returned the property declarations.

Step 11. Create GetCSharpType() method

In the above method, we used the GetCSharpType() method, so let's create it.
private static string GetCSharpType(string dataType, bool isNullable)
 {
     switch (dataType)
     {
         case "bigint":
             return isNullable ? "long?" : "long";
         case "int":
             return isNullable ? "int?" : "int";
         case "nvarchar":
         case "varchar":
             return "string";
         default:
             return "object";
     }
 }


In this method, I added a switch case in which according to database data type, I returned the appropriate C# data type corresponding to them.

Create a view of the CreateDynamicModel page
To create a view, right-click on CreateDynamicModel () method, click, 'Add View', and name the view, I named it 'CreateDynamicModel .cshtml'. Your view file is created

In CreateDynamicModel.cshtml
@model string

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Model Class</title>
</head>
<body>
    <h2>Dynamic Model Class</h2>
    <pre>
        @Html.Raw(Model)
    </pre>
</body>
</html>


In the above method, the string coming from the method is shown in the view inside <pre> tag. This will look like below.


Here, we've used C# MVC to successfully develop a dynamic model.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Consuming ASP.NET Web API REST Service In ASP.NET MVC Using HttpClient

clock March 28, 2024 10:10 by author Peter

In numerous forum postings, developers and students have addressed the same question: how to utilize Web API REST Service in an ASP.NET MVC application and how to initiate a call between them to exchange data. So, in response to this need, I decided to write this post to show how to use HttpClient to consume the ASP.NET Web API REST Service in an ASP.NET MVC application.

Prerequisites
If you're not sure what a Web API REST service is or how to construct, publish, and host an ASP.NET Web API REST Service, please watch my video and read the papers linked below. Follow the same steps if you want to learn how to create, host, and consume web API REST services in client applications.

In this article, we will use the same hosted Web API REST service to consume in our created ASP.NET MVC web application. Now, let's start consuming Web API REST service in the ASP.NET MVC application step by step.

Step 1. Create an MVC Application
Start, followed by All Programs, and select Microsoft Visual Studio 2015.
Click File, followed by New, and click Project. Select ASP.NET Web Application Template, provide the Project a name as you wish, and click OK.
After clicking, the following Window will appear. Choose an empty project template and check on the MVC option.

The preceding step creates the simple empty ASP.NET MVC application without a Model, View, and Controller, The Solution Explorer of created web application will look like the following.

Step 2. Install HttpClient library from NuGet
We are going to use HttpClient to consume the Web API REST Service, so we need to install this library from NuGet Package Manager .

What is HttpClient?

HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.
To install HttpClient, right click on Solution Explorer of created application and search for HttpClient, as shown in the following image.

Now, click on Install button after choosing the appropriate version. It will get installed after taking few seconds, depending on your internet speed.

Step 3. Install WebAPI.Client library from NuGet
This package is used for formatting and content negotiation which provides support for System.Net.Http. To install, right click on Solution Explorer of created application and search for WebAPI.Client, as shown in following image.


Now, click on Install button after choosing the appropriate version. It will get installed after taking few seconds depending on your internet speed. We have installed necessary NuGet packages to consume Web API REST services in web application. I hope you have followed the same steps.

Step 4. Create Model Class
Now, let us create the Model class named Employee.cs or as you wish, by right clicking on Models folder with same number of entities which are exposing by our hosted Web API REST service to exchange the data. The code snippet of created Employee.cs class will look like this.

Employee.cs
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

Step 5. Add Controller Class
Now, let us add ASP.NET MVC controller

After clicking Add button, it will show in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller .

Our hosted Web API REST Service includes these two methods, as given below.

  • GetAllEmployees (GET )
  • GetEmployeeById (POST ) which takes id as input parameter

We are going to call GetAllEmployees method which returns the all employee details ,The hosted web api REST service base URL is http://192.168.95.1:5555/ and to call GetAllEmployees from hosted web API REST service, The URL should be Base url+api+apicontroller name +web api method name as following http://192.168.95.1:5555/api/Employee/GetAllEmployees.

In the preceding url

  • http://localhost:56290 Is the base address of web API service, It can be different as per your server.
  • api It is the used to differentiate between Web API controller and MVC controller request .
  • Employee This is the Web API controller name.
  • GetAllEmployees This is the Web API method which returns the all employee list.

After modifying the code of Homecontroller class, the code will look like the following.

Homecontroller.cs
using ConsumingWebAapiRESTinMVC.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace ConsumingWebAapiRESTinMVC.Controllers
{
    public class HomeController : Controller
    {
        //Hosted web API REST Service base url
        string Baseurl = "http://192.168.95.1:5555/";
        public async Task<ActionResult> Index()
        {
            List<Employee> EmpInfo = new List<Employee>();
            using (var client = new HttpClient())
            {
                //Passing service base url
                client.BaseAddress = new Uri(Baseurl);
                client.DefaultRequestHeaders.Clear();
                //Define request data format
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //Sending request to find web api REST service resource GetAllEmployees using HttpClient
                HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");
                //Checking the response is successful or not which is sent using HttpClient
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;
                    //Deserializing the response recieved from web api and storing into the Employee list
                    EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);
                }
                //returning the employee list to view
                return View(EmpInfo);
            }
        }
    }
}


I hope, you have gone through the same steps and understood about the how to use and call Web API REST service resource using HttpClient .

Step 6. Create strongly typed View
Now, right click on Views folder of the created application and create strongly typed View named by Index by choosing Employee class to display the employee list from hosted web API REST Service, as shown in the following image.

Now, click on Add button. It will create View named index after modifying the default code. The code snippet of the Index View looks like the following.

Index.cshtml

@model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>
@{
    ViewBag.Title = "www.compilemode.com";
}
<div class="form-horizontal">
    <hr />
    <div class="form-group">
        <table class="table table-responsive" style="width:400px">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.City)
                </th>
            </tr>
            @foreach (var item in Model) {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.City)
                    </td>
                </tr>
            }
        </table>
    </div>
</div>


The preceding View will display all employees list . Now, we have done all the coding.

Step 7. Run the Application
After running the Application, the employee list from hosted web API REST service.

I hope, from the above examples, you have learned how to consume Web API REST Service in ASP.NET MVC using HttpClient.

Note

  • Download the Zip file of the Published code to learn and start quickly.
  • This article is just a guideline on how to consume Web API REST Service in ASP.NET MVC application using HttpClient.
  • In this article, the optimization is not covered in depth; do it as per your skills.




ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Passing Data from ASP.NET Core MVC to JavaScript: Using ViewBag and ViewData

clock March 20, 2024 07:39 by author Peter

This tutorial will focus on ASP.NET Core MVC; as developers, we can use ViewBag or ViewData to send data from the server to the client side. These protocols provide simple and efficient data transport to the client side without the need for sophisticated client-side frameworks or libraries. This article will look at how to pass ViewBag or ViewData to JavaScript in ASP.NET MVC and ASP.NET Core MVC, with code samples.


What are ViewBag and ViewData?

ViewBag and ViewData are classes supplied by the ASP.NET MVC framework that allow us to transmit data from the controller to the views. They are temporary data containers capable of storing any object and transferring data between the controller and display.

ViewBag in ASP.NET MVC framework
ViewBag is a dynamic object that can contain any object. It is a property of the ControllerBase class, which is the foundational class for all ASP.NET controllers. ViewBag is a dynamic object, which means it can be assigned any value at runtime.

ViewData in ASP.NET MVC framework
ViewData is a dictionary-like object that is part of the ViewDataDictionary class. ViewData is a collection of key-value pairs that can store any object. The keys are strings, while the values are objects.

How to pass data from ViewBag or ViewData to JavaScript?
ASP.NET Core MVC allows developers to send data from the server to the client using ViewBag or ViewData. These protocols provide simple and efficient data transport to the client side without the need for sophisticated client-side frameworks or libraries. This post will look at how to transmit data from ViewBag or ViewData to JavaScript in ASP.NET Core MVC, with code examples.

There are several ways to pass data from ViewBag or ViewData to JavaScript. Let's look at some of the most common methods.

Using a hidden input field
A hidden input field is a simple method for passing data from ViewBag or ViewData to JavaScript. In your view, you may add a hidden input field and set its value to the data you want to send. Then, in JavaScript, you can retrieve the value of the input field and use it as needed.

In ASP.NET Core MVC, the following example shows how to use a hidden input field to send data from ViewBag to JavaScript.

@{
    ViewBag.MyData = "Peter Blog Post";
}
<input type="hidden" id="my-data" value="@ViewBag.MyData" />
<script>
    var myData = document.getElementById("my-data").value;
    console.log(myData); // Output: "Ziggy, Rafiq Blog Post"
</script>


Using JSON serialization

Another way to pass data from ViewBag or ViewData to JavaScript is by serializing the data as JSON and then using it in your JavaScript code. This method is useful when passing more complex data types, such as objects or arrays.

Below is an example of using JSON serialization to pass data from ViewData to JavaScript in ASP.NET Core MVC.
@{
    ViewData["MyData"] = new { Name = "Lerzan", Age = 28 };
}
<script>
    var myData = @Html.Raw(Json.Serialize(ViewData["MyData"]));
    console.log(myData.Name); // Output: "Lerzan"
    console.log(myData.Age); // Output: 28
</script>


Using AJAX
Finally, AJAX can pass data from ViewBag or ViewData to JavaScript asynchronously. This method is useful when you want to load data dynamically from the server side without refreshing the page.

Below is an example of using AJAX to pass data from ViewBag to JavaScript in ASP.NET Core MVC.
@{
    ViewBag.MyData = "Peter Blog Post";
}

<script>
    $.ajax({
        url: '@Url.Action("GetData")',
        type: 'GET',
        data: { myData: '@ViewBag.MyData' },
        success: function (data) {
            console.log(data); // Output: "Peter Blog Post"
        }
    });

</script>
// Controller action method
public ActionResult GetData(string myData)
{
    return Content(myData);
}


In the example above, we use jQuery AJAX to call the "GetData" action method on the server side and pass the ViewBag data as a query string parameter. The server-side method returns the data as plain text, which is then logged to the console in the AJAX success callback.

Passing ViewBag Data to JavaScript
To pass ViewBag data to JavaScript, we can create a script block in the view and assign the value of ViewBag to a JavaScript variable. Here's an example below.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewBag.Message = "I am Peter";
        return View();
    }
}
@{
    ViewBag.Title = "Peter Website";
}
<script>
    var message = '@ViewBag.Message';
    alert(message);
</script>


In the above example, we assigned a value to ViewBag in the controller. Then we accessed the ViewBag data in the view by creating a script block and assigning the value to a JavaScript variable. We then displayed an alert box with the message value.
Passing ViewData Data to JavaScript

To pass ViewData data to JavaScript, we can create a hidden input field in the view and assign the value of ViewData to the field. We can then access the value of the hidden input field in JavaScript. Here's an example,
public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewData["Message"] = "This is Peter Blog Site";
        return View();
    }
}
@{
    ViewData["Title"] = "Peter Blog";
}
<input type="hidden" id="message" value="@ViewData["Message"]" />

<script>
    var message = document.getElementById("message").value;
    alert(message);
</script>


In the above example, we assigned a value to ViewData in the controller and then accessed the ViewData data in the view by creating a hidden input field and assigning the value to the field. We then accessed the value of the hidden input field in JavaScript and displayed an alert box with the message value.

Summary
To summarize, we looked at how to transmit data from ViewBag or ViewData to JavaScript in ASP.NET MVC and ASP.NET Core MVC. We discovered that using ViewBag and ViewData efficiently transports data from the server to the client side, making web applications more interactive and dynamic. We may quickly transmit data to the client without the use of sophisticated frameworks or libraries by converting data to JSON, giving values to JavaScript variables, or accessing data through hidden fields. These strategies can improve the user experience and result in more powerful and responsive web apps.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: In ASP.NET MVC, User Authentication is Combined with Forms Authentication

clock March 14, 2024 09:35 by author Peter

Forms Authentication is a popular approach in ASP.NET for managing user authentication within online applications. It enables developers to authenticate users using credentials saved in a database or another user store. This article will lead you through the process of implementing Forms Authentication in an ASP.NET web application with.NET Framework 4.8.0.

Step 1. Create a New ASP.NET Web Application
Open Visual Studio and create a new ASP.NET web application project, ensuring the selection of the appropriate framework version (in this case, .NET Framework 4.8.0).

Step 2. Configure Forms Authentication in web.config

Navigate to the web.config file of your ASP.NET application. Configure Forms Authentication by adding the following configuration within the <system.web> section:

<authentication mode="Forms">
    <forms loginUrl="~/Authority/Login" timeout="30"></forms>
</authentication>


This configuration specifies that Forms Authentication is enabled, the login page is Login.chtml, the default landing page after login is Default.chtml, and the session timeout is set to 30 minutes.

Step 3. Create a Login Page

Add a new web form named Login.chtml to your project. Design the login page with fields for username and password, as well as a login button.

Step 4. Implement Login Logic
In the code-behind file (Login.cs), implement the login logic when the user submits the login form.
using System.Web.Mvc;
using AdminPlain.Models;
using ApplicationDb.Operation;
using System.Web.Security;

namespace AdminPlain.Controllers
{
    [HandleError]
    public class AuthorityController : Controller
    {
        AdminPlainRepositery repo = null;
        public AuthorityController()
        {
            repo = new AdminPlainRepositery();
        }
        // GET
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(AuthorityMembers members)
        {
            var result = repo.FindUser(members);
            if (result)
            {
                FormsAuthentication.SetAuthCookie(members.Name, false);
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError("", "Invalid UserName and Password");
            return View();
        }
    }
}


Step 5. Create a Default Landing Page
Add another web form named Default.chtml to serve as the default landing page after successful login. This page can contain protected content that only authenticated users can access.

Step 6. Protect Pages
To protect pages that require authentication, you can use the Authorize attribute. Apply the [Authorize] attribute to the code-behind file of protected pages.
[Authorize]
public ActionResult Index(ApplicationModel detail)
{
    if (ModelState.IsValid)
    {
       var result = repo.addTask(detail);
       ViewBag.isSuccess = true;
    }else {
        ViewBag.isSuccess = false;
    }
    return View();
}

Step 7. Implement Logout Functionality
To allow users to log out, create a logout button or link that calls the SignOut method of the FormsAuthentication class.
public ActionResult Logout()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Login");
}


Forms Authentication in ASP.NET Framework 4.8.0 provides a straightforward method for implementing user authentication in web applications. By following the steps outlined in this guide, you can create a secure login system that protects sensitive areas of your application and provides a smooth user experience.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Perform Operations on WebForms From MVC

clock March 1, 2024 06:47 by author Peter

As you are aware, one of the most useful features in Visual Studio 2013 is "One ASP.NET," which allows us to construct an application using Web Forms, MVC, and Web API. We can build it all in a single application. When using all of these ASP.NET components within a single application, there may be a few alternatives, such as:

  • An existing Web Forms project can be configured with MVC functionality to generate modules
  • Modules can communicate with Web Forms and receive information from the MVC controller

There are various sections, as specified below, to construct the scenario in which we can pass data from the GridView to the new MVC controller and view it through the MVC View.

  • Creating an application
  • Adding MVC Controller and Models
  • Creating View
  • Run the application.

Creating an Application
In this section, we can build an empty project template and then use the ASP.NET wizard to add the Web Forms project using the steps below.
Step 1: Create an ASP.NET web application.
Step 2: Choose the empty project and online forms.

Step 3: Add the WebForm named DataWebForm to the project.

Step 4: Now add the GridView from the toolbox

Adding MVC Controller and Models

In this section we'll create the model and controller for the project using the following procedure.

Step 1: Add the ADO.NET Data Entity Model to the Models folder.

Step 2: Now configure the data model with the database table.

Step 3: Now configure the data source for the Grid View and then add the Button template filed inside the GridView with the following code:
<asp:TemplateField ShowHeader="false">
    <ItemTemplate>
        <asp:Button ID="BtnEdit" Text="Edit" PostBackUrl="Cricketer/Edit" runat="server" />
    </ItemTemplate>
</asp:TemplateField>


In the code above we have set the PostBackUrl property to the Edit View page. We'll create it in the following procedure.

Step 4: Now run the application

Step 5: Now add the following code of HiddenField and Literal after the GridView control:
<asp:HiddenField ID="FormToMVC" runat="server" />
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>


Step 6: Add the jQuery to the Scripts folder. You can download it. Modify your page head part with the following code:
<head runat="server">
    <title>WebForms To MVC</title>
    <script src="Scripts/jquery-2.0.3.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("input:submit").click(function (evt) {
                var Cric_Data = {};
                Cric_Data.ID = $(evt.target).closest("tr").children("td:eq(0)").html();
                Cric_Data.Name = $(evt.target).closest("tr").children("td:eq(1)").html();
                Cric_Data.Team = $(evt.target).closest("tr").children("td:eq(2)").html();
                Cric_Data.Grade = $(evt.target).closest("tr").children("td:eq(3)").html();
                $("#FormToMVC").val(JSON.stringify(Cric_Data));
            });
        });
    </script>
</head>


In the code above you can see that the ready handler is used to handle the click event for all buttons in the form and if the edit button is selected by the user then it creates the JavaScript object and sets the properties, like id, name and so on to the values from a GridView row. The closest method gets the reference of the table row for editing and then the html method returns the data inside the GridView.

Step 7: Now we create a new folder named Controllers and add a new scaffolded item


Note: Please build the solution before scaffolding.

Step 8: Create a Empty MVC 5 Controller.
Add Scaffold in MVC 5

This will add the Content, App_Start,  fonts and Views folders to the project automatically. Now modify your controller with the code below:
using Newtonsoft.Json;
using System.Web.Mvc;
using WebFormsToMvcApp.Models;
namespace WebFormsToMvcApp.Controllers
{
    public class CricketerController : Controller
    {
        //
        // GET: /Cricketer/
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Edit()
        {
            string Jason_Data = Request.Form["FormToMVC"];
            Cricketer CricObj = JsonConvert.DeserializeObject<Cricketer>(Jason_Data);
            return View(CricObj);
        }
        public void Update(Cricketer CricObj)
        {
            CricketerSite_Entities CricDb = new CricketerSite_Entities();
            Cricketer Cric_Exist = CricDb.Cricketers.Find(CricObj.ID);
            Cric_Exist.Name = CricObj.Name;
            Cric_Exist.Team = CricObj.Team;
            Cric_Exist.Grade = CricObj.Grade;
            CricDb.SaveChanges();
            Response.Redirect("/DataWebForm.aspx?cricketerid=" + CricObj.ID);
        }
    }
}

In the code above, the Edit action method is used to read the JSON data sent from the webform and then the JSON.NET library is used to desterilize the JSON string ("FormToMVC") into the Cricketer class object.

We have also created the Update() to get the information of the Edit() View. It receives the data as the Cricketer object. It simply applies the changes to the database.

Step 9: Modify the Global.asax file with the following code:
using System;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace WebFormsToMvcApp
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


Creating View
In this section we'll create the view for the controller using the following procedure.
Step 1: Right-click on the Edit method for adding the view.

Step 2: Edit and modify the view with the following code:
@model WebFormsToMvcApp.Models.Cricketer
@{
    ViewBag.Title = "Edit Cricketer";
}
<h2>Edit</h2>
@using (Html.BeginForm("Update","Cricketer",FormMethod.Post))
{
    <div class="form-horizontal">
        <h4>Cricketer</h4>
        <hr/>
        <div class="form-group">
            @Html.LabelFor(model=> model.ID)
            <div class="col-md-10">
                @Html.TextBoxFor(model=> model.ID)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Name)
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Name)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Team)
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Team)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Grade)
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Grade)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-10">
                <input type="submit" value="Update" />
            </div>
        </div>
    </div>
}

The code defined above submits the data to the Update method.

Step 3: Now at last add the following code to the DataWebForm's Page_Load() event:
public partial class DataWebForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["cricketerid"]))
        {
            Literal1.Text = "Cricketer" + Request.QueryString["cricketerid"] + "Updated Successfully";
        }
    }
}


That's it. You can see the following figure of Solution Explorer to view the entire project:


Running the Application
Step 1: Run the DataWebForm and click on the Edit button to update the data
Step 2: Update the info and click on the Update



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Various Return Types From MVC Controller

clock February 23, 2024 07:11 by author Peter

This is a popular question in.NET job interviews, as I've heard from several acquaintances. Developers with limited hands-on expertise with MVC should be able to respond to the question because the scenario is typical and requires returning anything from the controller to the presentation environment on a regular basis. We are extremely familiar with the "ActionResult" class, which is the base class for many classes and can return an object from those classes. The class structure is as follows:

System.Object
System.Web.Mvc.ActionResult

    System.Web.Mvc.ContentResult
    System.Web.Mvc.EmptyResult
    System.Web.Mvc.FileResult
    System.Web.Mvc.HttpStatusCodeResult
    System.Web.Mvc.JavaScriptResult
    System.Web.Mvc.JsonResult
    System.Web.Mvc.RedirectResult
    System.Web.Mvc.RedirectToRouteResult
    System.Web.Mvc.ViewResultBase


In this example, we will see all of the derived classes that is inherited from the “ActionResult” base class. So, let's start one by one.
 
Return View
This is a most common and very frequently used type. We see that we can pass eight parameters when we return the view. We can specify the view name explicitly or may not.

Return partial View

The concept of a partial view is quite similar to the master page concept used in Web Form applications. The partial view is simply a pagelet that may be returned from the controller and combines with the main view to create a single tangible HTML page.

It may require four parameters to render in the partial view.
 
Redirect
This is comparable to the Response.redirect() and Server.Transfer() routines. It uses the URL path to redirect, however with MVC, we can instead use Response.Redirect() or Server.Transfer() instead.

Redirect To Action
Sometimes it is necessary to call another action after completion of one action, this is very similar to a function call in traditional function oriented programming or Object Oriented Programming. It may take 6 parameters. The first parameter is very simple, only action name.

Return content
This is useful when we want to return a small amount of strings from a controller/action. It takes three parameters. The first one is a simple string and the remaining two are strings with little information.

Return JavaScript
When we wanted to return a JavaScript string, we may use this function. It takes only one parameter, the string only.

Return File
We are allowed to return a binary file if needed from a controller. It takes 6 parameters maximum.

Conclusion
Those are all of the return types in an action in an MVC controller, but we rarely use them; in my limited experience, users prefer to return View() from the action. What say you? Have fun learning.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Result vs. ActionResult in ASP.NET MVC

clock February 7, 2024 08:54 by author Peter

ViewResult and ActionResult are two classes in ASP.NET MVC that are used to display the output of an action function.

1. Action-Result
For all action result kinds in ASP.NET MVC, ActionResult is the abstract base class. It serves as the foundation class for many result kinds, including JsonResult, ViewResult, and RedirectResult. Usually, you specify ActionResult as the return type when you define an action method in a controller.

As an illustration

public ActionResult MyAction()
{
    // Action logic here
    return View(); // Returns a ViewResult
}

2. ViewResult
ViewResult is a specific type of ActionResult that represents a result that renders a view. When you return a ViewResult from an action method, it means that the framework should render a view associated with the action.

For example

public ViewResult MyAction()
{
    // Action logic here
    return View(); // Returns a ViewResult
}

Key differences in nutshell

The following are the key differences in nutshell.

  • ActionResult is more general: ActionResult is a more general type, and it can represent different types of results, not just views. It allows for flexibility in returning various result types.
  • ViewResult is specific to views: ViewResult is a specific type derived from ActionResult and is used when you specifically want to return a view from an action method.
  • ViewResult simplifies return type: If your action method is intended to return a view, using ViewResult directly can make your code more explicit and easier to understand.
  • ActionResult provides more options: If your action method needs to return different types of results based on certain conditions, using ActionResult allows you to return different types of results (e.g., RedirectResult, JsonResult, etc.) from the same action.

Moreover, in practice, you can often use ViewResult directly when you know your action will always return a view. If you need more flexibility or want to return different types of results, using ActionResult allows for that versatility.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Data Transfer Using TempData in ASP.NET Core MVC Controllers

clock January 30, 2024 06:34 by author Peter

Using TempData, you may transfer temporary data between controllers in ASP.NET Core MVC. A dictionary called TempData can be used to transfer information between controllers both during the current request and the one that comes after. Here's how you can make this happen.

Configure the First Controller's TempData
Assign the data you wish to pass to the TempData in your first controller action.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Student student)
{
    if (ModelState.IsValid)
    {
        _context.Add(student);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    // Transfer the Complete Student Object to the Teacher
    TempData["student"] = student;
    return RedirectToAction("Index","Teacher");
}

Complete Student Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DataTransferBetweenControllersinASPNETCoreMVC.DatbaseContext;
using DataTransferBetweenControllersinASPNETCoreMVC.Models;

namespace DataTransferBetweenControllersinASPNETCoreMVC.Controllers
{
    public class StudentsController : Controller
    {
        private readonly AppDbContext _context;

        public StudentsController(AppDbContext context)
        {
            _context = context;
        }

        // GET: Students
        public async Task<IActionResult> Index()
        {
            return View(await _context.Students.ToListAsync());
        }

        // GET: Students/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .FirstOrDefaultAsync(m => m.Id == id);
            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

        // GET: Students/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Students/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Student student)
        {
            if (ModelState.IsValid)
            {
                _context.Add(student);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            // Transfer the Complete Student Object to Teacher
            TempData["student"] = student;
            return RedirectToAction("Index","Teacher");
        }

        // GET: Students/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students.FindAsync(id);
            if (student == null)
            {
                return NotFound();
            }
            return View(student);
        }

        // POST: Students/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,RollNo,Section,Program")] Student student)
        {
            if (id != student.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(student);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!StudentExists(student.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(student);
        }

        // GET: Students/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .FirstOrDefaultAsync(m => m.Id == id);
            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

        // POST: Students/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var student = await _context.Students.FindAsync(id);
            if (student != null)
            {
                _context.Students.Remove(student);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool StudentExists(int id)
        {
            return _context.Students.Any(e => e.Id == id);
        }
    }
}


Retrieve TempData in the Second Controller
In your second controller action, retrieve the TempData.
// GET: Teachers
public async Task<IActionResult> Index()
{
    // Recieve the Student Object data and then keep the data
    // Keep TempData for the next request
    var studentData = TempData["student"];
    TempData.Keep();
    return View(await _context.Teachers.ToListAsync());
}


Complete Teacher Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DataTransferBetweenControllersinASPNETCoreMVC.DatbaseContext;
using DataTransferBetweenControllersinASPNETCoreMVC.Models;

namespace DataTransferBetweenControllersinASPNETCoreMVC.Controllers
{
    public class TeachersController : Controller
    {
        private readonly AppDbContext _context;

        public TeachersController(AppDbContext context)
        {
            _context = context;
        }

        // GET: Teachers
        public async Task<IActionResult> Index()
        {
            // Recieve the Student Object data and then keep the data
            var studentData = TempData["student"];
            TempData.Keep();
            return View(await _context.Teachers.ToListAsync());
        }

        // GET: Teachers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teachers
                .FirstOrDefaultAsync(m => m.Id == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // GET: Teachers/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Teachers/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,Course,Department")] Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                _context.Add(teacher);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(teacher);
        }

        // GET: Teachers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teachers.FindAsync(id);
            if (teacher == null)
            {
                return NotFound();
            }
            return View(teacher);
        }

        // POST: Teachers/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Course,Department")] Teacher teacher)
        {
            if (id != teacher.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(teacher);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TeacherExists(teacher.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(teacher);
        }

        // GET: Teachers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teachers
                .FirstOrDefaultAsync(m => m.Id == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // POST: Teachers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var teacher = await _context.Teachers.FindAsync(id);
            if (teacher != null)
            {
                _context.Teachers.Remove(teacher);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool TeacherExists(int id)
        {
            return _context.Teachers.Any(e => e.Id == id);
        }
    }
}


Keeping TempData for Subsequent Requests
By default, TempData is meant for a single subsequent request. If you want to persist TempData for more than one subsequent request, you can use the Keep method.
// GET: Teachers
public async Task<IActionResult> Index()
{
    // Recieve the Student Object data and then keep the data
    var studentData = TempData["student"];
    TempData.Keep();
    return View(await _context.Teachers.ToListAsync());
}

Conclusion

TempData is an efficient way to pass temporary data across controllers in ASP.NET Core MVC. You can save and retrieve information for the current request and the one that follows using TempData. You can enable data sharing between several components of your application by setting TempData in one controller and retrieving it in another.

Keep in mind that TempData is only meant to be read once before being marked for deletion. If you need to store the data for more than one request, use the Keep method.

A handy way to share transient data between controllers when a user interacts with your ASP.NET Core MVC application is via TempData.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Using Postman for ASP.NET MVC 5 API Testing

clock January 11, 2024 06:50 by author Peter

Developers can send calls to an API and receive results using Postman, a popular tool for testing APIs. It offers an easy-to-use interface for creating, testing, and documenting RESTful web services. We will look at using Postman for API testing in an ASP.NET MVC 5 application in this article.

Required conditions
    Postman installed on your computer and an ASP.NET MVC 5 project setup in Visual Studio
    basic familiarity with API development and ASP.NET MVC

Configuring the API
Step 1: Launch Visual Studio, then open the ASP.NET MVC 5 project template.
Step 2: Right-click on the "Controllers" folder and choose "Add" > "Controller" to add a new Controller to the project.

Step 3: Build and launch the program to make sure everything is operating as it should.

Postman is Used for API Testing
Step 1: Launch Postman and click the "New" dropdown menu, then choose "Request" to start a new request.
Step 2: Type your API endpoint's URL into the address bar.
Step 3: From the dropdown menu next to the address bar, choose the HTTP method you wish to use (GET, POST, PUT, DELETE, etc.).

Click on the appropriate tabs to add headers, query parameters, or request body data, if necessary.

Step 4: To send the request and get the answer, click the "Send" button.
The response's headers, content, and status code will all be shown in the lower panel.

Examining Various API Techniques

  • GET Request: Just enter the API URL and choose the GET method to test a GET request. If necessary, you can add query parameters.
  • POST Request: Choose the POST method and input the API URL to test a POST request. Using the "Body" tab, add request body data and select the desired format (x-www-form-urlencoded, form-data, raw, etc.).
  • PUT Request: Choose the PUT method, input the API URL, and supply the request body data in order to test a PUT request.
  • DELETE Request: Choose the DELETE method and input the API URL to test a DELETE request.

Managing the Authentication Process
You can add authentication headers or tokens in Postman if your API requires authentication. Before submitting the request, add the required authentication information in the "Authorization" or "Headers" tab.

Examining the Reaction

Postman presents the body, headers, and response status code in an organized manner. By examining the status code and contrasting it with the anticipated outcome, you may verify the response. You can also use XPath or JSONPath syntax to extract particular data from the response body.

Postman can make API testing more simpler and is a very useful tool for this purpose. In this post, we looked at using Postman to test an ASP.NET MVC 5 application's API. You may easily test various API methods, manage authentication, and examine the answer by following the above-described processes.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Handle CORS Error ASP.NET MVC

clock December 15, 2023 06:00 by author Peter

CORS: What is it?
CORS is a security feature of browsers that regulates the sharing of resources, such as images or data, across websites from different domains (e.g., example.com vs. api.example.com). In order to stop unwanted cross-domain queries, it enables servers to whitelist particular domains for resource access. Consider it a data passport that guarantees secure connections between websites.

Because browsers save a ton of personal information, such as cookies, for every website, CORS issues can be a pain. An unscrupulous website has the ability to take over your browser session and maybe steal sensitive data from reliable websites if CORS limitations are not properly implemented.

Set your server to accept requests from the origin of your front end to resolve CORS difficulties in Next.js and React.

We will set up our asp.net web API to do this in this tutorial.

Step 1: Create an attribute to handle and preprocess the request.


In the Generated Class File, add this code snippet.
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}


Step 2. Bind with Action

[AllowCrossSiteJson]
public ActionResult About()
{
DataTable dms = repo.getpro();
string json = JsonConvert.SerializeObject(dms);
return Content(json);
}


We've tackled the notorious CORS beast in this article, explaining its complexities and giving you the tools to set up your ASP.NET MVC 5 Web API so that it works flawlessly with JavaScript frameworks like ReactJS. You've made it possible for secure, seamless communication between your dynamic client-side apps and your server-side API by putting these tips into practice.

Recall the main conclusions.

  • Setting the right headers to allow cross-origin requests from the server side is known as "configuring access-control headers."

Keep in mind that security is crucial. As alluring as "AllowAnyOrigin" may be, think about customizing your CORS setup to meet your unique requirements so that only allowed origins have access to your sensitive information.

We really hope that this post has helped you in your CORS journey. Please feel free to post a remark below if you have any queries or difficulties, and our community will be pleased to help!



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in