【问题标题】:JQuery Ajax model not opening in ASP.NET Core MVC applicationJQuery Ajax 模型未在 ASP.NET Core MVC 应用程序中打开
【发布时间】:2022-11-01 10:42:05
【问题描述】:

我已经尝试了几个小时来获得一个模式来打开并显示来自控制器中的 GET Action 方法的数据。

这是 jQuery 函数:

test = (url, id) => { 

        $.ajax({
            type: 'GET',
            url: url,
            data: {
                'id': id
            },
            success: function (res) {
                console.log(res);
                $("#formModal").find(".modal-body").html(res.Id);
                $("#formModal").find(".modal-title").html(res.Name);
                $("#formModal").modal('show');
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                console.log(response);
                alert("error");
            }
        })
    };

这是我认为调用该函数的代码:

<a asp-action="Index" 
   onclick="test('@Url.Action("GetStudies", "Studies", null, Context.Request.Scheme)', '@item.NodeId')">
   <i class="fa-solid fa-square-poll-horizontal" 
      style="color:darkolivegreen"></i>
</a>

控制器如下所示:

[HttpGet]
public async Task<IActionResult> GetStudies(int id)
{
    var results = (from t in _context.Studies
                   where !((from s in _context.Studies
                            join sn in _context.StudyNodes on s.Id equals sn.StudyId
                            where sn.NodeId == id
                            select s.Id).ToList()).Contains(t.Id)
                   select new Study
                          {
                              Id = t.Id,
                              Name = t.Name
                          }).ToList();

    return Ok(results);
}

我在另一篇文章中发现我应该使用 return ok(results) 而不是 View() 但这没有任何区别。视图中的按钮将我带到控制器,结果查询按原样完成,但看起来没有响应或至少没有响应被传递回 jQuery 函数。

我想要做的是在模态表中显示结果,所以我的猜测是结果是 jQuery 函数无法识别的形式,但我是新手,需要一些指导。

【问题讨论】:

    标签: jquery ajax asp.net-core-mvc


    【解决方案1】:

    请确保您的 JQuery 函数可以正确获取您的 Url 和 id。

    如果还是不行,可以试试function test(url,id) {}

    然后将a标签替换为button

    <button asp-action="Index" type="button"
       onclick="test('@Url.Action("GetStudies", "Studies", null, Context.Request.Scheme)', '@item.NodeId')">
       <i class="fa-solid fa-square-poll-horizontal" 
          style="color:darkolivegreen"></i>
    </button>
    

    这在我的测试中运行良好。你可以试一试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多