通过ViewBag将值从控制器传递到视图

本文关键字:视图 控制器 ViewBag 通过 | 更新日期: 2023-09-27 18:01:44

所以我有一个控制器,我似乎可以理解如何传递一个参数到我的ActionResult方法。

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

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

[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)。

我错过了什么?

通过ViewBag将值从控制器传递到视图

视图中的链接(或带有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]方法

您必须从HttpGet 'SearchAction'方法传递值。如果从它传递,则只有值将显示在视图

中。
[HttpGet]
public ActionResult Search()
{
    ViewBag.iD = your Id value here;
    return View();
}

在初始加载时将调用get方法,在提交时只调用post方法。

On your view

<a href='@Url.Action("ActionName", "ControllerName", new { id= 10})'>...</a>

 @{ 
int id = 10 
}
    <a href="/ControllerName/ActionName/@id"> ... </a>

On Your Action

Public ActionResult Search(int id)
{
Viewbag.Id = id;
return view();
}

Action是默认的[HTTPGET]你不需要提到它