c# - 通过 ViewBag 将值从 Controller 传递到 View

标签 c# asp.net-mvc

所以我有一个 Controller ,我似乎可以理解如何将参数传递给我的 ActionResult 方法。

routes.MapRoute(
            name: "MyRoute",
            url: "{controller}/{name}/{id}",
            defaults: new { controller = "Project", name = "Search", id = UrlParameter.Optional }
        );

这是我的路线。现在在我的 Controller 中我创建了一个方法

[HttpGet]
public ActionResult Search()
{
    return View();
}

[HttpPost]
public ActionResult Search(int Id)
{
    ViewBag.iD = Id;
    return View();
}

在我看来

<body>
    <div>
        ASDF + @ViewBag.iD
    </div>
</body>

如何将值从搜索操作传递到我的 iD 参数?似乎无论我怎么称呼
http://localhost:52992/Project/Search/id=2http://localhost:52992/Project/Search/1

两种方法都进入 Search() 方法,没有一个进入 Search(int iD)。

我错过了什么?

最佳答案

View 中的链接(或带有 FormMethod.Get 的表单或在地址栏中输入 url)会进行 GET 调用,而不是 POST,因此您的方法应该是

[HttpGet]
public ActionResult Search(int ID)
{
    // do something based on the value of ID
    ViewBag.iD = ID;
    return View();
}

并删除[HttpPost]方法。

关于c# - 通过 ViewBag 将值从 Controller 传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38867975/

相关文章:

c# - FFMPEG - windows - MJPEG 流 - 转换为 MP4 并重新流式传输 - C# - 新手

c# - 我可以在 EF 6 中将 Fluent API 与注释属性混合使用吗?

asp.net - 如何撤销/无效/取消旧的电子邮件确认 token (身份)

c# - 如何对在C#中使用LINQ使用反射找到的属性进行排序?

c# - 自动设置 ASP.Net App_Sprites 权限

c# - 如何访问 Windows 8 应用程序历史记录? (来自代码 c++/c#/winapi)

c# - LINQ DataTable Sum In Where 子句

c# - DataGridTextColumn 不允许输入 "double"值

asp.net-mvc - asp.net mvc 4 通过按钮从 Controller 调用方法

c# - 无法让 Entity Framework MVC 应用程序将数据播种到数据库