所以我有一个 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=2
或http://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/