ASP.NetMvc如何使用Ajax将数据从View通过按钮传递到Controller



我有一个按钮,它从模型中获取数据并将其传递到Ajax函数中。然后,这个函数应该调用一个控制器,但它没有,并且永远不会命中控制器上的断点。

参数取自Model(均为字符串(的按钮:

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

Ajax函数:

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

控制器(还有其他方法,但我在这里省略了它们(:

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

我还应该补充一点,我正在使用Asp.Net Core MVC,并使用Clean Architecture,我对这两方面都非常陌生。

您可以使用这种替代方式通过AJAX将数据发送到您的Controller方法:

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>

控制器方法:

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

将ajax的dataType更改为'json'

相关内容

  • 没有找到相关文章