【问题标题】:ASP.Net Mvc How to pass data from View into Controller with a Button using AjaxASP.Net Mvc 如何使用 Ajax 将数据从 View 传递到带有 Button 的控制器
【发布时间】:2022-01-15 03:07:54
【问题描述】:

我有一个按钮,它从模型中获取数据并将其传递给 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,并且在这两方面都是超级新手。

【问题讨论】:

    标签: c# html ajax asp.net-mvc asp.net-core


    【解决方案1】:

    您可以使用这种替代方式通过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
            }
        }
    }
    

    【讨论】:

    • 感谢您的回复!但是,这似乎仍然不起作用。当我单击按钮时,没有弹出成功消息并且没有命中断点。
    • @KondVideos 我已经更改了 ajax 请求,因此删除了 dataType 并指定了 contentType。我还根据需要为按钮添加了 HTML。现在试试。另请查看您是否在 Web 浏览器的开发者控制台上收到任何错误。
    • 我已经更新了函数,我得到:Uncaught ReferenceError: PassHwData is not defined at HTMLButtonElement.onclick when press the button
    • @KondVideos 这是一个范围界定问题。您需要检查在哪里定义 PassHwData 方法以及按钮单击事件是否可以访问它。更多信息:stackoverflow.com/questions/41527655/…
    • 当然,不能放弃投票但标记为正确:)
    【解决方案2】:

    将 ajax 的 dataType 更改为 'json'

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多