0

我有一个 MVC 应用程序,当单击链接时,需要根据另一个页面上的相同值显示页面。我不知道为什么传递的是 null 而不是字符串。我的代码如下。

控制器:

public string searchQ
    {
        get { return (string)Session["searchQ"]; }
        set { Session["searchQ"] = value; }
    }

    public ActionResult Index()
    {
        Session["InitialLoad"] = "Yes";
        return View();
    }


    [HttpPost]
    public ActionResult Index(string heatSearch)
    {
        ViewBag.SearchKey = heatSearch;
        searchQ = heatSearch;
        return View();
    }


    public ActionResult Index_Perm()
    {
        ViewBag.SearchKey = searchQ;

        return View();
    }






    public ActionResult PartialMainLim(string heatSearch)
    {
        HomeModel C = new HomeModel();
        ChemViewModel D = new ChemViewModel();
        D = C.QueryResults(heatSearch);

        return PartialView(D);
    }


    public ActionResult PartialMain(string heatSearch)
    {
        HomeModel C = new HomeModel();
        ChemViewModel D = new ChemViewModel();
        D = C.QueryResults(heatSearch);

        return PartialView(D);
    }

索引视图中的代码如下所示(这个有效):

@if (ViewBag.SearchKey != null)
{
    <div>
    @Html.Action("PartialMainLim", "Home", (string)ViewBag.SearchKey)
    </div>
 }

在 index_perm 视图中:

@if(ViewBag.SearchKey != null)
{
    <div>
    @Html.Action("PartialMain", "Home", (string)ViewBag.SearchKey)
    </div>
 }

当我在两个视图中检查 SearchKey 的值时,它是正确的。然而,尽管 SearchKey 是正确的,但对于“PartialMain”方法,传递的是 null 而不是字符串。不过,这一切都适用于另一种观点。我究竟做错了什么?

4

3 回答 3

2

将值传递回控制器时,您基本上有两种选择:

  1. 制作表格

  2. 将其作为 url 的一部分传递

Get 方法只接受 url 属性,而 Post 方法也能够处理表单内容。

从你想做的事情来看,我想说你可以使用类似的东西:

@Html.Action("PartialMain", "Home", new {heatSearch = (string)ViewBag.SearchKey})

这应该创建的 url 看起来像 /Home/PartialMain?heatSearch=[content of SearchKey]

编辑:

这只会传递 ViewBag 中存在的值。您从 Session 中得到它,这在 MVC 中是一个糟糕的想法(应该是无会话的)。请考虑您是否真的需要它。通常还有其他方法可以实现这一点。

于 2013-04-19T07:10:40.153 回答
0

我认为这个问题是你的会话将是空的。框架 ASP.NET MVC 的原则之一是无状态。在 ASP.NET MVC 中使用会话非常可怕。

目前,我认为您可以通过使用默认使用 Session 的TempData快速修复它。您可以查看一篇过时的文章以进一步挖掘ViewData 与 TempData

于 2013-04-19T01:06:23.540 回答
0

单击 index_perm 视图时,控制器中没有 HttpPost 处理程序。

于 2013-04-19T00:45:03.297 回答