2

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 Answers 2

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
        }
    }
}
14
  • 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. Commented Jan 14, 2022 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. Commented Jan 14, 2022 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 Commented Jan 14, 2022 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: stackoverflow.com/questions/41527655/… Commented Jan 14, 2022 at 17:11
  • 1
    Sure thing, can't give upvotes yet but marked as correct :) Commented Jan 14, 2022 at 18:54
0

change dataType of ajax to 'json'

1
  • 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.
    – Community Bot
    Commented Jan 15, 2022 at 2:46

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.