如何使用RedirectToAction将对象作为隐藏参数传递?

10K*_*KY4 8 asp.net-mvc

我这样做了.

public ActionResult GetInfo(SomeModel entity)
{
     ----
     return RedirectToAction("NewAction", "NewController", new System.Web.Routing.RouteValueDictionary(entity));
}
Run Code Online (Sandbox Code Playgroud)

被称为的行动

public ActionResult NewAction(SomeModel smodel)
{
     -------
     -------
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我可以在浏览器地址栏上看到所有发布的参数值,如何在浏览器中隐藏这些查询字符串参数值.

http://localhost:51545/NewController/NewAction?SurveyID=13&CatID=1&PrimaryLang=1&SurveryName=Test%20Survery&EnableMultiLang=False&IsActive=False
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Kar*_*sla 11

在你的情况下,而不是使用RouteValueDictionary和从querystring尝试传递模型TempData(因为当我们使用RedirectToAction时,它将生成一个新的http请求,对象路由将显示在url中,因此它不是在url中显示敏感数据的好方法).

使用TempData如下: -

public ActionResult GetInfo(SomeModel entity)
{
  ----
  TempData["entity"] = entity; //put it inside TempData here
  return RedirectToAction("NewAction", "NewController");
}

public ActionResult NewAction()
{
   SomeModel smodel = new SomeModel();
   if(TempData["entity"] != null){
   smodel = (SomeModel)TempData["entity"];  //retrieve TempData values here
   }
   -------
   -------
}
Run Code Online (Sandbox Code Playgroud)

使用的好处TempData这里是,它会保留其值一个重定向,而且模型将被私自运到另一个控制器动作,一旦你读取数据TempData其数据将被自动设置,如果你想保留TempData阅读它,然后使用后价值TempData.keep("entity").


要么

如果您的视图位于同一个控制器中,那么这是一个解决您问题的简单方法:

public ActionResult GetInfo(SomeModel entity)
{
  ----
  return NewAction(entity);
}

public ActionResult NewAction(SomeModel smodel)
{
   -------
   -------
  return View("NewAction",smodel)
}
Run Code Online (Sandbox Code Playgroud)

正如@ Chips_100正确评论所以我在这里包括它: - 第一个解决方案将进行真正的重定向(302),它将更新用户浏览器中的URL.第二种解决方案将提供所需的结果,同时将原始URL保留在地址栏中.