Creating a POST request in a C# web application

I am currently attempting to submit a form using C#

After conducting some research, I have been having trouble coding it correctly (as I am new to this field).

Below are the snippets of code I have:

View;

<form>
          <div class="field-wrap">
              <label>
                  Email Address<span class="req">*</span>
              </label>
              <input type="email" id="input-username" name="Username" required autocomplete="on" />
          </div>

          <div class="field-wrap">
            <label>
              Password<span class="req">*</span>
            </label>
            <input type="password" id="input-password" name="Password" required autocomplete="on"/>
          </div>

          <p class="forgot"><a href="#">Forgot Password?</a></p>

          <button class="button button-block" id="button-login">Log In</button>

      </form>

Controller;

// GET: User
        [HttpPost]
        public ActionResult Login()
        {
            string username = Session["Username"].ToString();
            string password = Session["Password"].ToString();

            Service iLocationService = new Service();
            var result = Service.MemberGetLogin( username, password, "127.0.0.1" );

            ViewBag.Message = result;

            return View();
        }

Javascript;

jQuery(document).ready(function () {
$("#button-login").click(function () {
    $.ajax({
        type: "POST",
        url: "/Controllers/UserController/login/",
        data: $(this).serialize(),
        dataType: "json"
    })
    .done(function (result) {
        console.log(result);
    })
    .fail(function (a) {
        console.log( a);
    });
});

});

The goal is to send a POST request with the input values to validate the user.

Thank you in advance

Answer №1

Take a look at this particular line

string username = Session["Username"].ToString();

In the provided code snippet, an attempt is being made to retrieve the username and password values from Session variables. The query arises as to who actually assigned the user name and password to the Session? It is recommended to extract these values from the posted form instead.

[HttpPost]
public ActionResult Login(string userName, string password)
{
  // Perform operations with userName and password, then return something
}

Furthermore, it's crucial to ensure that the form itself is serialized, not just the clicked button. A suggested approach involves employing Html helper method for generating the form tag within the Razor view, dynamically setting the action attribute value in the accompanying JavaScript code rather than hardcoding URLs.

This can be implemented in the following manner:

@using(Html.BeginForm("login", "User"))
{
    // Include your existing form inputs here
   <button class="button button-block" id="button-login">Log In</button>
}

Regarding script handling:

$("#button-login").click(function () {
     $.ajax({
        type: "POST",
        url: $(this).closest("form").attr("action"),
        data: $(this).closest("form").serialize()           
     })
});

Considering the ajax form submission, incorporating a JSON response from the server is advised for better client-side processing:

[HttpPost]
public ActionResult Login(string userName, string password)
{
   if (userName and password are valid)
       return Json(new { Status="success"});
   else
         return Json(new { Status="failed", Message="Invalid credentials"});
}

Upon completion of the request, the done callback should evaluate the response and trigger appropriate actions:

.done(function (result) {
   if(result.Status === "success")
   {
     window.location.href = "/Home/Index"; // Redirect as necessary
   }
   else
   {
     alert(result.Message);
   }    
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The process of defining JSON data from a web API within React using Axios

Seeking assistance with ASP.NET Web API and ReactJS integration using Axios to read JSON data. Below is an example of the JSON data: [ { "id": 1, "name": "Count Duck", "age": 3 }, { "id": 4, "name": "Cou ...

Ways to transfer data through the javascript success function in traditional CodeIgniter

Currently, I am working with an aging CodeIgniter application. I am trying to implement an onchange function that retrieves data from the controller and displays it in an input field that is part of an array. This is a snippet of the code on the view page ...

Is there a way to manually or forcibly expire the access-token generated by my web API?

When developing a web API in ASP.NET, the system generates an access token that is stored in browser cache or session storage. However, there is a risk of someone stealing this access token and exposing the API data using tools like Fiddler or Postman. H ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

HTML5 video player with secondary playlist

Looking for a videoplayer setup where there are two playlists, but only one can play at a time. When choosing a video from the first list initially, nothing happens. However, after selecting a video from the second list, the first list starts working. HTM ...

Using AJAX to create an interactive dropdown menu with changing options

I have been working on creating a dropdown menu using Ajax. When hovering over the navigation bar, the menu successfully triggers the Ajax function to display the dropdown options. The issue arises when attempting to navigate to another page (show_activi ...

PHP function with JSON response encountered an error during the AJAX call

I am currently working on creating a News Ticker that utilizes PHP, Javascript, and AJAX. The first step involved creating a PHP function called getFeed(), which gathers data from various news websites into an Array. This data is then returned in JSON form ...

The definition of require is missing in the MEAN stack node

Currently experimenting with building an application on the MEAN stack and encountered a hurdle involving the use of Node's require function. Here is my current project structure: -- app -- images -- scripts -- app.js // configuration fi ...

Is there a more efficient way to consolidate multiple functions like this into one cohesive function instead of having to define each one separately?

After attempting to implement a loop without success, I also considered using regex but that did not work either. The code in question is part of a larger project that involves dynamically adding and deleting fields using jQuery. The classes and ids used f ...

The error message "Unable to map props.theTodos" is displayed

I'm facing an error message while compiling: "TypeError: props.theTodos.map is not a function". I've been struggling with this issue for quite some time, but I haven't found a solution yet as I'm using hooks instead of class components. ...

Local Bootstrap notifications functioning correctly, but failing to display on the server

I successfully set up notifications in a localhost application, and they were functioning perfectly. However, after uploading to the server, the notifications stopped displaying without any changes being made. The application consists of two main files: ...

Interaction of PHP and JavaScript when a new row is inserted using JavaScript

I have encountered an issue with the following PHP code snippet: PHP Code: <?php $output['house_sitting_date_yes_no']=$_POST['house_sitting_date_yes_no']; if(file_exists('../feeds/ptp-ess_landing_house.json')){ ...

modifying a model across multiple interfaces

My goal is to make modifications to a model in multiple views. Due to the complexity of my models with numerous properties, I need to edit them across different views. For example: The first page edits 2 properties, the second page edits 3 other propertie ...

AngularJS ng-click function not functioning as expected when used within ng-repeat

The event.id is correctly displayed in the html text, but the function does not receive it properly. Even though it appears correctly in the source code, there seems to be an issue here. <span ng-repeat="event in [{"id":"dxczhlyvmblc","name":"4 on 4 - ...

Accessing a document using protractor

It seems like every protractor example I come across online uses browser.get with a web URI. browser.get('http://localhost:8000'); I want to use Selenium to navigate to a local file:// path without needing a web server running. Just a simple HT ...

Large data sets may cause the Highchart Bar to not display properly

Currently, I am working on a web project that displays traffic usage in chart mode using Highchart Bar. The issue I am facing is that there are no errors thrown when running this code. <script type="text/javascript"> $(function () { $(&apos ...

Transferring information from Vue Component to Vuex storage

I am currently working with a Laravel API route that looks like this: Route::get('c/maintenances/{contractor_user_id}', 'Maintenance\Api\ApiContractorMaintenanceController@index'); The contractor_user_id parameter is dynamic ...

Utilizing Object Arrays in Chart.js for Optimal Performance

I'm struggling with using chart.js to create charts for my admin panel. I'm having trouble figuring out how to properly utilize my JSON array of objects in order to generate the correct dataset. What exactly should I be putting in the data field ...

When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is. Here is my class: export default { name: "Contact", component ...