繁体   English   中英

值未从视图正确传递给控制器

[英]Value not being passed properly to controller from view

我有一个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的值时,它是正确的。 但是,对于方法“PartialMain”,只要SearchKey正确,就会传递null而不是字符串。 这一切都适用于其他视图。 我究竟做错了什么?

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

  1. 做一个表格

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

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

从你想要做的事情我会说你可以使用类似的东西:

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

这应该创建看起来像/ Home / PartialMain的网址?heatSearch = [SearchKey的内容]

编辑:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM