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 :: 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!



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Model Binders for ASP.NET MVC with Examples

clock September 15, 2023 06:57 by author Peter

ASP.NET MVC (Model-View-Controller) is a popular web development framework for creating strong and maintainable web applications. Model Binders are an important part of it. Model Binders play a critical role in mapping incoming HTTP requests to action method parameters, making it easier to work with client-side data. In this blog post, we will delve into the world of ASP.NET MVC Model Binders and present practical examples of how to use them.

What Exactly Are Model Binders?
Model Binders are ASP.NET MVC components that are responsible for mapping data from numerous sources, such as form fields, query strings, route parameters, and JSON payloads, to action method parameters. They are critical in easing the process of taking user input and transforming it into highly typed objects that your program may use.

Here's a detailed breakdown of how Model Binders work:

  • A user delivers an HTTP request to your ASP.NET MVC application, generally via a form submission or an API call.
  • Routing: The MVC framework uses routing rules to identify which controller and action method should handle the request.
  • Model Binders are useful in this situation. They collect data from the HTTP request and transfer it to the action method's arguments. The mapping is based on the names and types of parameters.
  • Execution of Action Methods: After the data is bound to the action method parameters, the method is executed using the provided data.
  • The action method processes the data and provides a response, which is returned to the client.

Now, let's look at some real-world examples of Model Binders.

Binding to Simple Types as an Example
Assume you have a simple HTML form with a single text input field named "username." You wish to capture the user's entered username.
public ActionResult Register(string username)
{
    // Process the username
    return View();
}

In this scenario, the Model Binder automatically binds the username parameter based on the name of the form input field.

Example 2: Complex Type Binding
Model Binders can also be used to tie complex types, such as custom classes, to action method parameters. Consider the following User class:

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


You can bind an instance of the User class from a form submission as follows:
public ActionResult CreateUser(User user)
{
    // Process the user object
    return View();
}

The Model Binder will automatically populate the User object's properties using the submitted form data.
Example 3. Custom Model Binders

In some cases, you might need to implement custom Model Binders to handle complex scenarios. For example, if you want to bind data from a non-standard source or perform custom data transformation, you can create a custom Model Binder.
public class CustomBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // Custom logic to bind the model
        // Example: Read data from a cookie and populate the model
    }
}


To use the custom Model Binder, you can decorate your action method parameter with the [ModelBinder] attribute:

public ActionResult MyAction([ModelBinder(typeof(CustomBinder))] MyModel model)
{
    // Custom binding logic applied
    return View();
}

ASP.NET MVC Model Binders are critical components that let you manage user input data in your online applications. They make it simple to convert HTTP request data to action method parameters, making it easier to work with user-supplied data. Model Binders provide a strong technique for streamlining data binding in your ASP.NET MVC applications, whether you're dealing with simple types or complex objects.

You can design more efficient and maintainable web apps with ASP.NET MVC if you understand how Model Binders function and use them effectively.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Simple Login Application using Sessions in ASP.NET MVC

clock September 1, 2023 10:10 by author Peter

Step: Design your Database
Create the UserProfile table using the following script.
    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  
    Select 'peter', 'pete1234', 1 Union All  
    Select 'scott', 'scott1234', 1 Union All  
    Select 'laura', 'laura1234', 1


Step 1: Create Project
Go to FILE, New, then click on Project.

Select Visual C#, Web under Installed templates. After that select ASP.NET MVC 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 Click OK.

Step 2: Add Entity Data Model
Go to Solution Explorer, Right Click on Project, Add, then select ADO.NET Entity Data Model.

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

Select Generate from 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 User name 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 radio button: 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.

Step 3: Add a Controller
Go to Solution Explorer, Right click on 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");  
                }  
            }  
        }  
    }  


Step 4: 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 Strongly Typed View
    View Name must be an action method name.
    Select view engine as Razor.
    Select Create a strongly typed view CheckBox .
    Select Model class as UserProfile (MvcLoginAppDemo)
    Select Scaffold template as Empty
    Click on Add

And 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)  
    {  
    <div style="border: 1px solid red">  
    @ViewBag.Message  
    </div>  
    }  
    <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>  


Step 5: 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).

Step 6: Run the Application
Provide the user credentials and click on OK. If you provide the valid user credentials then the user name will be displayed on your dashboard.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Using an ASP.NET MVC Application, Create a WEB API POST Method to Retrieve Data from a SQL Database

clock August 24, 2023 07:58 by author Peter

In this post, I'll show you how to use an ASP.NET MVC application to establish a WEBAPI POST function to extract data from a SQL database.

Open SQL Management Studio, then create a new table and write the table's stored procedure.
Table column names and datatypes are determined by your needs.

Create proc [dbo].[UserInfo]
(
@UserName nvarchar(100)
)
as
(
select UserId,UserName,Address,IsActive,UserTypeId from WebAPI
where
UserName=@UserName
)


Once you have successfully created the SQL store procedure then Create a new MVC WebAPI Application using visual studio.
provide the project name and project location.

Choose Empty project, then select the MVC and WEB API options from the essential references column on the right.

Now the project has been created successfully.

After you've created the project, right-click on the Models folder, select Add, and then New item. In the Models Folder, place the class file.

From the C# node then choose the class definition and provide the class file name UserEntity.cs. Once we added the class file to our project solution.

Use the below code in UsersEntity.cs file.
using Microsoft.SqlServer.Server;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.Office.SharePoint.Tools;
using static System.Net.Mime.MediaTypeNames;
using System.Data;

namespace SampleWebAPI.Models
{
    public class UsersEntity
    {

        public string UserId { get; set; }

        public string UserName { get; set; }

        public string Address { get; set; }

        public string UserTypeId { get; set; }

        public string IsActive { get; set; }

        public UsersEntity()
        {

        }
     }

}

Likewise create a new logger.cs and ErrorDetails.cs class file to capture the logs and error details in the Models folder.

Use the below code in Logger.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SampleWebAPI.Models
{
    public class Logger
    {
         // To capture the log details
        #region "-- Class Level Variable / Object Declaration --"
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion
        #region "-- Public Functions --"
        public static void LogError(string msg, Exception ex)
        {
            logger.Error(msg, ex); //This for error msg
        }
        public static void LogDebug(string msg, Exception ex)
        {
            logger.Debug(msg, ex);
        }
        public static void LogFatal(string msg, Exception ex)
        {
            logger.Fatal(msg, ex);
        }
        public static void LogInfo(string msg)
        {
            logger.Info(msg);
        }
        public static void LogWarn(string msg, Exception ex)
        {
            logger.Warn(msg, ex);
        }
        public static void LogInfo(string msg, Exception ex)
        {
            logger.Info(msg, ex);
        }
    }
    #endregion
}


Use the below code in ErrorDetails.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SampleWebAPI.Models
{
//This Class used for error msg
    public class ErrorDetails
    {
        public List<string> schemas { get; set; }
        public string details { get; set; }
        public int status { get; set; }
    }
}

Then add the controller to the Controller folder.
Right Click on the Controller folder, choose to add, and click Controller.
Click the MVC empty read and write controller file.

Then give the controller name based on your requirement.

Once the Controller has been created successfully, we can write the Controller methods in the controller.
Use the below code in the controller.
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SampleWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using Microsoft.Office.SharePoint.Tools;
using static System.Net.Mime.MediaTypeNames;

namespace SampleWebAPI.Controllers
{
    public class UserController : ApiController // To Initialize the Web API
    {
        [System.Web.Http.AcceptVerbs("GET", "POST")] // To check the result in browser
        [System.Web.Http.HttpPost] //To check the Post method
        [System.Web.Http.Route("users/info")] //This the route url
        public JObject info(string UserName)
        {
            ErrorDetails objErrorDetail = new ErrorDetails();
            string jsonResponse = string.Empty;
            JObject jsonObject = null;


            try
            {
                Logger.LogInfo("info: starting to get user list info");
                DataSet ds = new DataSet();
                UsersEntity objUserDetail = new UsersEntity();
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString ="Data Source=Test;" +"Initial Catalog=Test;" +"User id=Test;" + "Password=Test;";

                {
                  //Sql connection from the database
                    using (SqlCommand cmd = new SqlCommand("UserInfo", conn))
                    {
                        conn.Open();
                        Logger.LogInfo("info: Sql Connection established.");
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@UserName",UserName);
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(ds);
                        conn.Close();
                        Logger.LogInfo("info: Sql Connection closed.");

                    }
                }

                if (ds.Tables[0].Rows.Count >= 1)
                {
                    Logger.LogInfo("info: starting to format the json.");
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // Display the column in the output page using object dataset.
                        List<string> lst = new List<string>();
                        objUserDetail.UserName = dr["UserName"].ToString();
                        objUserDetail.UserId = dr["UserId"].ToString();
                        objUserDetail.Address = dr["Address"].ToString();
                        objUserDetail.UserTypeId = dr["UserTypeId"].ToString();
                        objUserDetail.IsActive = dr["IsActive"].ToString();
                        jsonResponse = JsonConvert.SerializeObject(objUserDetail);
                        // Deserialize the JSON API response into a JObject
                        jsonObject = JsonConvert.DeserializeObject<JObject>(jsonResponse);
                        // Serialize the updated object back to JSON
                        string updatedJsonResponse = jsonObject.ToString();

                    }
                    Logger.LogInfo("info: data formatted in json successfuly.");
                    return jsonObject;
                }
                else
                {
                    Logger.LogInfo("info: User not found returned null data.");
                    List<string> lst = new List<string>();
                    lst.Add("urn:ietf:params:scim:api:messages:2.0:Error");
                    objErrorDetail.schemas = lst;
                    objErrorDetail.status = (int)HttpStatusCode.NotFound;
                    objErrorDetail.details = "User Not Found";
                    return JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(objErrorDetail));
                }
            }
            catch (Exception ex)
            {
                Logger.LogInfo("info: Error occured.");
                Logger.LogError("info: Error - " + ex.Message, ex);
                jsonObject = null;
                List<string> lst = new List<string>();
                lst.Add("urn:ietf:params:scim:api:messages:2.0:Error");
                objErrorDetail.schemas = lst;
                objErrorDetail.status = (int)HttpStatusCode.InternalServerError;
                objErrorDetail.details = ex.Message.ToString();
                return JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(objErrorDetail));
            }

        }

    }
}



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Creating Dynamic Dropdown Lists in ASP.NET MVC Using AJAX

clock August 14, 2023 09:43 by author Peter

Introduction: In this article, we will explore how to implement dynamic dropdown lists in an ASP.NET MVC application. We'll use jQuery AJAX to fetch data from the server and populate dependent dropdown lists based on user selections. The provided code includes examples of how to create cascading dropdowns for countries, states, and cities, allowing users to select specific locations for student data.


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

Building the Dropdown Form
Building the Dropdown Form: In the "Index.chtml" file, we have designed a form to collect student data, including cascading dropdowns for countries, states, and cities.
<!-- Index.chtml -->
<!-- ... (existing code) ... -->
<div class="text-light text-center my-3 d-flex justify-content-center gap-3">
    <div>
        @if (ViewBag.Country != null)
        {
            @Html.DropDownListFor(x => x.Country, ViewBag.Country as SelectList, "Select Country", new { @class = "form-control" })
        }
    </div>
    <div class="stateSection">
        <span id="states-loading-progress" style="display: none;">Please wait for State..</span>
        @Html.DropDownListFor(x => x.State, ViewBag.State as SelectList, "Select State", new { @class = "form-control" })
        @Html.ValidationMessageFor(x => x.State)
    </div>
    <div class="citySection">
        <span id="states-loading-progress" style="display: none;">Please wait for City..</span>
        @Html.DropDownListFor(x => x.City, ViewBag.City as SelectList, "Select City", new { @class = "form-control" })
        @Html.ValidationMessageFor(x => x.City)
    </div>
</div>
<!-- ... (existing code) ... -->


Implementing AJAX for Dropdowns
Implementing AJAX for Dropdowns: In the JavaScript section, we've added AJAX functions to handle the country and state dropdowns dynamically.
/*------ Country Function -------*/
$("#Country").change(function () {
    var stateID = $(this).val();
    $('#State').empty();
    $('#City').addClass('d-none');

    console.log(stateID);

    var statesProgress = $("#states-loading-progress");
    statesProgress.show();

    if (stateID > 0) {
        $(".stateSection").addClass('active');

        $.ajax({
            type: "GET",
            url: "/Home/GetStateById/" + stateID,
            success: function (data) {
                $("#State").html('');

                var defaultOption = "<option value>Select State</option>";
                $("#State").append(defaultOption);

                $.each(data, function (id, option) {
                    var optionHtml = "<option value=" + option.StateID + ">" + option.StateName + "</option>";
                    $("#State").append(optionHtml);
                });

                statesProgress.hide();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('State function failed');
                statesProgress.hide();
            }
        });
    } else {
        $(".stateSection").removeClass('active');
        $(".citySection").removeClass('active');
        $.notify("Please select a Country", "error");
    }
});


/*------ State Function -------*/
$("#State").change(function () {
    $('#City').removeClass('d-none');
    var cityID = $(this).val();
    var statesProgress = $("#states-loading-progress");
    statesProgress.show();

    if (cityID > 0) {
        $(".citySection").addClass('active');

        $.ajax({
            type: "GET",
            url: "/Home/GetCityById/" + cityID,
            success: function (data) {
                $("#City").html('');

                var defaultOption = "<option value>Select City</option>";
                $("#City").append(defaultOption);

                $.each(data, function (id, option) {
                    var optionHtml = "<option value=" + option.Id + ">" + option.CItyName + "</option>";
                    $("#City").append(optionHtml);
                });

                statesProgress.hide();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('City function failed');
                statesProgress.hide();
            }
        });
    } else {
        $(".citySection").removeClass('active');
        $.notify("Please select a State", "error");
    }
});


Handling Dropdown Requests in the Controller
Handling Dropdown Requests in the Controller: In the "HomeController," we've added action methods to retrieve country, state, and city data from the database and return them as JSON results for the AJAX requests.
// Home Controller Method
public class HomeController : Controller
{
    public ActionResult Index()
        {
            List<CountryTable> CountryList = db.CountryTable.ToList();
            ViewBag.Country = new SelectList(CountryList, "Id", "countryName");

            List<StateTable> StateList = db.StateTable.ToList();
            ViewBag.State = new SelectList(StateList, "StateID", "StateName");

            List<CityTable> CityList = db.CityTable.ToList();
            ViewBag.City = new SelectList(CityList, "Id", "CItyName");

            return View();
        }

        public JsonResult GetStateById(int ID)
        {
            db.Configuration.ProxyCreationEnabled = false;
            var stateList = db.StateTable.Where(x => x.CountryID == ID).ToList();
            return Json(stateList, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetCityById(int ID)
        {
            db.Configuration.ProxyCreationEnabled = false;
            var CityList = db.CityTable.Where(x => x.StateID == ID).ToList();
            return Json(CityList, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditStudent(int ID)
        {
            var result = repo.EditFunction(ID);
            // Set selected values for the dropdown lists
            List <CountryTable> CountryList = db.CountryTable.ToList();
            ViewBag.CountryList = new SelectList(CountryList, "Id", "countryName", result.Country);

            List<StateTable> StateList = db.StateTable.ToList();
            ViewBag.StateList = new SelectList(StateList, "StateID", "StateName", result.State);

            List<CityTable> CityList = db.CityTable.ToList();
            ViewBag.CityList = new SelectList(CityList, "Id", "CItyName", result.City);

            return View(result);
        }
    }
}


Conclusion: In this article, we have learned how to create dynamic dropdown lists with cascading behavior in an ASP.NET MVC application using AJAX. The JavaScript AJAX functions communicate with the server to fetch data based on user selections, and the ASP.NET MVC controller methods handle the requests and return JSON results. By following this guide, you can enhance your web application with more interactive features and improve the user experience with dynamic dropdowns. Happy coding!



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