【问题标题】:Pass in data parameters to new MVC ActionResult call without showing in URL将数据参数传递给新的 MVC ActionResult 调用而不显示在 URL 中
【发布时间】:2021-08-20 02:43:24
【问题描述】:

我正在添加一个新的 MVC 页面,并让方法和调用启动并运行。我的问题是我不想传递 URL 参数以显示在我的页面中,但在我重定向到我的新页面时需要传递该方法的参数。目前我的设置是这样的:

Page.cs

void ToNewPage()
{
 Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName", ID1 = 1, ID2 = 2 });
}

ControllerName.cs

public ActionResult ActionName(int ID1, int ID2)
    {
         ...
        return View(model);
    }

目前使用我的代码,我得到了 URL ~/ControllerName/ActionName?ID1=1&ID2=2。我只是希望 URL 只是 ~/ControllerName/ActionName。我知道这在前端或通过 javascript 会更容易,但如果可能的话,需要从 ToNewPage 方法执行此操作。

【问题讨论】:

  • 如果您必须从 Page.cs 中创建两个公共变量;否则,我会从 .cshtml 文件中调用该操作,并将其传递给您的 ViewModel。
  • TempData 或 Cookie 值得考虑。但老实说,查询字符串(即你现在正在做什么)是最好的解决方案。

标签: c# asp.net-mvc url actionresult


【解决方案1】:

有工作代码:

PageController.cs

public class PageController : Controller
  {
      // GET: Page
      public ActionResult Index()
      {
          return View();
      }

      public ActionResult ToNewPage()
      {
          var ids = Newtonsoft.Json.JsonConvert.SerializeObject(new { ID1 =  1, ID2=  2 });
          TempData["ids"] = ids;
          return RedirectToAction("Index", "NewPage");
      }
  }

NewPageController.cs

public class NewPageController : Controller
{
    // GET: NewPage
    public ActionResult Index()
    {
        if (TempData["ids"] != null)
        {
            dynamic ids = JsonConvert.DeserializeObject(TempData["ids"] as string);
            ViewBag.ID1 = ids.ID1;
            ViewBag.ID2 = ids.ID2;
        }
        return View();
    }
}

NewPage\Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>NewPage</h2>
<ul>
    <li>ID1: @ViewBag.ID1</li>
    <li>ID2: @ViewBag.ID2</li>
</ul>

【讨论】:

    【解决方案2】:

    你应该使用 TempData:

    void ToNewPage()
    {
      TempData["ID1"]="ID1 Value"
      TempData["ID2"]="ID2 Value"
      Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName"
      });
    }
    
    public ActionResult ActionName()
    {
        int ID1=int.parse(TempData["ID1"].ToString());
        int ID2=int.parse(TempData["ID2"].ToString());
    
        return View();
    }
    

    您可以在许多控制器中填充许多 TempData,并在许多视图和控制器中使用它们

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多