【问题标题】:HTML.ActionLink to Controller using Ajax to prevent postbackHTML.ActionLink 到控制器使用 Ajax 防止回发
【发布时间】:2013-02-28 21:10:27
【问题描述】:

这是我认为的 ASP MVC 代码。它触发到控制器并传递assetId和relationshipContext:

 @Html.ActionLink("Archive", "Archive", new { assetId = Model.ID, relationshipContext = assetTypeRelation.RelationshipContextID }, new { @class = "btn btn-mini btn-warning", id = "btnArchive" })

我想通过这个 HTML.ActionLink 使用 Ajax,但有点困惑。这是我开始使用的 jQuery。基本上我只需要这个 actionlink 来将assetId 和relationshipContext 传递给我的assetcontroller 中的Archive 方法。

$('#btnArchive').click(function(){
                  $.ajax({
                      url: '@Url.Action("Archive", "Archive")',
                      type: 'POST',
                      dataType: 'json',
                      data: {
                          assetId: $(this).attr("assetId"),
                          relationshipContext: $(this).attr("relationshipContext"),
                      },
                      success: function(){
                          alert("success")
                      },
                      error: function () {
                          alert("error")
                      },

                  });

【问题讨论】:

  • 我不认识顶部的那种语言。我做了一个谷歌搜索,发现它是 asp.net 的一部分,特别是 mvc 部分。我添加了 asp.net-mvc 标记,但您可能想在代码中添加一些解释。
  • 您想混合使用服务器端和客户端代码。
  • 感谢您添加附加标签,我更新了问题的正文。

标签: jquery ajax asp.net-mvc html.actionlink


【解决方案1】:
【解决方案2】:

您的 AssetController 操作方法是什么样的?我应该看起来像:

[HttpPost]
public ActionResult Archive(int assetId, string relationshipContext)
{
     //do some work
     return Content("true");
}

另外,您在 @Url.Action 调用中调用了错误的控制器。您的视图代码可能需要更改为

$('#btnArchive').click(function(){
                  $.ajax({
                      url: '@Url.Action("Archive", "Asset")',
                      type: 'POST',
                      dataType: 'json',
                      data: {
                          assetId: $(this).attr("assetId"),
                          relationshipContext: $(this).attr("relationshipContext"),
                      },
                      success: function(data){
                          alert(data)
                      },
                      error: function () {
                          alert("error")
                      },

                  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2021-10-23
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多