Home > Mobile >  ASP.Net Mvc How to pass data from View into Controller with a Button using Ajax
ASP.Net Mvc How to pass data from View into Controller with a Button using Ajax

Time:01-15

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  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.

CodePudding user response:

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

HTML:

<button  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
        }
    }
}
  •  Tags:  
  • Related