1

I have a button that takes data from a Model and passes it into an Ajax function. This function should then call a controller, but it doesn't and a breakpoint on a controller is never hit.

The button with parameters taken from Model (both are strings):

<button class="btn btn-primary btn-lg active" onclick="PassHwData(@obj.Name,@obj.HomeWorldBonus)" >Choose @obj.Name</button>

the Ajax function:

<script>
          function PassHwData(name, hwBonus)
          {
              $.ajax({
                  url: '@Url.Action("Create", "HomeWorld")',
                  type: "POST",
                  data: {'name' : name, 'hwBonus' : hwBonus}
                  datatype: "text",
                  success: function(name, hwBonus)
                  {
                      document.getElementById('success').innerHTML += success {name}{hwBonus};
                  }
              })
          }
</script>

<div id=success>
      success: 
</div>

The Controller (there are other methods but I omitted them here):

using DarkHeresy.Application.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DarkHeresy.Web.Controllers
{
    [Authorize]
    public class HomeWorldController : Controller
    {
        private readonly IHomeWorldService _homeWorldService;
        public HomeWorldController(IHomeWorldService homeWorldService)
        {
            _homeWorldService = homeWorldService;
        }
        [HttpPost]
        public async Task<IActionResult> Create(string name, string hwBonus)
        {
            return View(await _homeWorldService.UpdateCharacterList()); //this will have implementation later
        }
    }
}

I should also add that I am using Asp.Net Core MVC and going with Clean Architecture and am super new at both of those things.

2 Answers2

0

You can use this alternative way to send the data via AJAX to your Controller method:

HTML:

<button class="btn btn-primary btn-lg active" onclick="PassHwData('@obj.Name','@obj.HomeWorldBonus')" >Choose @obj.Name</button>

AJAX:

<script>
          function PassHwData(name, hwBonus)
          {
              console.log(name);
              console.log(hwBonus);
              var json = {
                   name : name,
                   hwBonus : hwBonus
              };
              
              $.ajax({
                  type: "POST",
                  url: "@Url.Action("Create", "HomeWorld")",
                  dataType: "json",
                  data: {"json": JSON.stringify(json)},
                  success: function(name, hwBonus)
                  {
                      document.getElementById('success').innerHTML += success {name}{hwBonus};
                  }
              })
          }
</script>

<div id="success">
      success: 
</div>

Controller method:

using DarkHeresy.Application.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json; //For .NET CORE

namespace DarkHeresy.Web.Controllers
{
    [Authorize]
    public class HomeWorldController : Controller
    {
        private readonly IHomeWorldService _homeWorldService;
        public HomeWorldController(IHomeWorldService homeWorldService)
        {
            _homeWorldService = homeWorldService;
        }
        
        [HttpPost]
        public async Task<IActionResult> Create(string json)
        {
            var jsondata = JsonSerializer.Deserialize<dynamic>(json);
            //Get your variables here from AJAX call
            var name = jsondata["name"];
            var hwBonus = jsondata["hwBonus"];
            return View(await _homeWorldService.UpdateCharacterList()); //this will have implementation later
        }
    }
}
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
  • Thanks for the reply! However this still doesn't seem to work. The success message doesn't pop and the breakpoint isnt't hit when I click the button. – Kond Videos Jan 14 '22 at 16:53
  • @KondVideos I have changed the ajax request so the dataType is removed and the contentType is specified. I have also added the HTML for the button as required. Try now. Also see if you are getting any error on the developer console on the web browser. – Rahul Sharma Jan 14 '22 at 16:55
  • I've update the functions and I am getting: Uncaught ReferenceError: PassHwData is not defined at HTMLButtonElement.onclick when pressing the button – Kond Videos Jan 14 '22 at 17:08
  • @KondVideos It's a scoping issue. You need to check where you are defining your `PassHwData` method and if it accessible to the button click event. More information: https://stackoverflow.com/questions/41527655/uncaught-referenceerror-function-is-not-defined-at-htmlbuttonelement-onclick – Rahul Sharma Jan 14 '22 at 17:11
  • Ok the problem was a wrong syntax at `document.getElementById('success').innerHTML += success {name}{hwBonus};` Now the json string passes but is comes through as null so there must still be an issue somwhere. – Kond Videos Jan 14 '22 at 17:20
  • @KondVideos Updated answer and removed contenttype and reverted back to original answer. Also make sure that the values of `name` and `hwBonus` are coming correctly. Check the console to see if the values are being printed to the console. – Rahul Sharma Jan 14 '22 at 17:22
  • Thank you for all the help so far! The string now passes correctly into the method and jsondata gets set as `ValueKind = Object : "{"name":"mytext","hwBonus":"mytext"}.` However when the code reaches `var name` it stops executing and `name` stays as null. – Kond Videos Jan 14 '22 at 17:40
  • @KondVideos Well, can you try: `var name = jsondata.name;` – Rahul Sharma Jan 14 '22 at 17:44
  • Still doesn't work, I am getting an IDE0059: Unnecessary assignment of value to 'x' on both variables. – Kond Videos Jan 14 '22 at 17:56
  • @KondVideos Not sure about that. I do not see the variable `x` in the code that you have posted. – Rahul Sharma Jan 14 '22 at 18:01
  • Sorry for misunderstanding, I meant that x stand for names of the variables.The errors are `IDE0059: Unnecessary assignment of value to 'name'` and `IDE0059: Unnecessary assignment of value to 'hwBonus'` – Kond Videos Jan 14 '22 at 18:04
  • @KondVideos Okay, you can refer to this answer on how to serialize a dynamic JSON string: https://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net . Basically you have got the data in your `Controller`. Now you only need to de-serialize it as required. – Rahul Sharma Jan 14 '22 at 18:12
  • @KondVideos If my answer helped you out, don't forget to up-vote and mark it as correct. Thanks – Rahul Sharma Jan 14 '22 at 18:19
  • 1
    Sure thing, can't give upvotes yet but marked as correct :) – Kond Videos Jan 14 '22 at 18:54
0

change dataType of ajax to 'json'

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 15 '22 at 02:46