【问题标题】:passing parameter through @Html.ActionLink in asp.net core mvc在 asp.net core mvc 中通过@Html.ActionLink 传递参数
【发布时间】:2021-01-21 01:16:44
【问题描述】:

首先,我想澄清一下,我完全知道有很多类似的问题,但没有一个对我有用。

我正在尝试在我的 ASP.NET Core 3.1 MVC 应用程序中使用 @Html.ActionLink。

我从控制器接收一个 id 并将其保存在我的视图中的变量中

@{
   string attachmentToFecth = Model.AttachmentId;
 }

稍后我试图通过 ActionLink 将它传递给我的控制器以获取一些这样的数据

@Html.ActionLink("", "Details", "MarketPlace",
                     new { xid = attachmentToFecth }, null)

我的控制器功能是这样的

    [HttpGet]
    public ActionResult GetImages(string xid)
    {
        List<string> Images = new List<string>();
        var userID = _applicationUser.Users.FirstOrDefault(obj => obj.UserName == User.Identity.Name).UserId;

        var displayImages = (from images in _context.Attachments
                             join imageID in _context.InfoProducts on images.AttachmentId equals imageID.AttachmentId
                             
                             select new
                             {
                                 images.AttachmentPath
                             });

        return View(displayImages);
    }

当我在 ActionLink 处设置断点时,我可以看到预期的 id 正在接收中

新的 { xid = attachmentToFecth }

但是控制器中的 string xid 正在返回 null 值。

我在这里做错了什么?

注意忽略控制器内部的代码,它不完整,因为需要 xid 来完成它。

【问题讨论】:

  • GetImages 操作的路径是什么?如果它是默认的{controller}/{action}/{id?}',则路由需要名为id 的参数,而不是xid。因此它忽略了xid 参数。
  • 它使用默认路由。并将参数作为 id 而不是 xid 传递也不起作用。它仍然收到 null。
  • 您是否在浏览器中按 F12 以检查生成的 url?它是什么样的?它可以在我的项目中运行良好。并且您的操作名称是 GetImages,但您在锚点中使用了详细信息。我建议您可以尝试创建一个新项目并测试它是否有效。如果仍然无效,请您将新的 repo 分享给我们吗?

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


【解决方案1】:

你可以试试这样的吗?

@Html.ActionLink("My Link", "GetImages","MarketPlace" new { id = attachmentToFecth  }, null)

public async Task<Actionresult> GetImages(string id)
{
    // Do stuff with the id
}

还可以查看这篇文章的答案

Pass parameter to controller from @Html.ActionLink MVC 4

【讨论】:

  • 我已经检查了您提供的链接。对我来说,我的代码看起来与那里给出的答案相同,但不知何故它仍然不起作用。但是,如果您不介意,请将其更改为 async 对我的事业有何帮助。
  • 从您的示例代码中,您从 ActionLink 调用“详细信息”操作,但您提供了 GetImages 方法。这只是示例还是真实代码?还要检查控制器名称,“MarketPlaceController”看起来很正常。
  • 哦,是的。我现在看到了。我正在改变它并再次尝试。
  • 我解决了这个问题,但我没有使用操作链接,而是使用 ajax 请求从数据库中获取我的数据。
  • 恭喜@Mill3r
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多