Asp.net MVC 将数据从一种方法传递到另一种方法,然后传递到视图

Asp.net MVC passing data from one method to another method then to a view

我对将数据从一个 ActionResult 方法传递到另一个 ActionResult 方法感到困惑。

让我描述一下这是什么,

我需要将值从一种方法传递到另一种方法,并且该值必须在我从另一种方法呈现的视图中可用。

我在我的项目中看到的是这个(这是编辑,但是 [HttpPost] 编辑,它也重定向到编辑,但是 [HttpGet] 代替了 [HttpPost]):

TempData["Success"] = True;
return RedirectToAction("Edit/" + customer.Id, "Customer");

然后做了什么 [HttpGet] 编辑:

 if (TempData["Success"] != null && TempData.ContainsKey("Success"))
 ViewBag.Success = Convert.ToString(TempData["Success"]);
 return View(model);

正如你们在 [HttpPost] 上看到的,TempData["Success"] 设置为 True; 并且重定向到 [HttpGet] 方法并编写了下一个代码:

if (TempData["Success"] != null && TempData.ContainsKey("Success"))
 ViewBag.Success = Convert.ToString(TempData["Success"]);
 return View(model);

所以我想知道为什么需要设置 TempData 然后根据 TempDate 的值让我们将值设置为 ViewBag,我不能只设置值吗ViewBag 在重定向之前在我的第一个 ActionResult 上,因此它也可以在 View 上使用,即使视图是 rendered/called 来自 HttpGet 操作结果?

例如:

而不是这个:

TempData["Success"] = True;
return RedirectToAction("Edit/" + customer.Id, "Customer");

我可以简单地写在我的 HttpPost

ViewBag.Success = True;
return RedirectToAction("Edit/" + customer.Id, "Customer");

或者这需要使用 TempData 来完成,因为如果我不在重定向到 View 的 ActionResult 上赋值,ViewBag 将不会在 View 上可用,在本例中是 HttpGet 而不是 HttpPost(这意味着我需要在 HttpGet 上设置 ViewBag 值?)

如果我必须这样做,我也可以使用两个 ViewBag,而不是 ViewBag 和 TempData?

为什么有人会这样解决呢?这是正确的方法还是什么?

有几种技术可以实现 Post/Redirect/Get 模式。

TempData 是为单个重定向传递信息的一种方式。这种方法的缺点是,如果用户在最终重定向页面上点击刷新 (F5),他将无法再提取数据,因为后续请求的数据将从 TempData 中消失。

其他两种方法是查询字符串参数和持久化。

can't I just set value of ViewBag on my first ActionResult before redirection so it can be available also on a View

你不能,因为 Http 是无状态的。所以,我们使用TempData来存储临时数据,以便持久化Http请求。

And why would someone solve it like this at all? Is this correct approach or what?

就 ASP.NET MVC 而言,您采用的方法很好,因为我们没有其他方法可以在 Http 请求之间保留 临时 数据。

如果您发现自己经常这样做,您可能要考虑使用 alert extension methods 在烤面包机内显示消息。

Usage

[HttpPost]
public ActionResult Edit(SettingModel model)
{
   if (ModelState.IsValid)
   {
       ...
      return RedirectToAction("List")
          .WithSuccess($"Setting was updated successfully.");
   }
   return View(model);
}

第一个 ViewBag 在这种情况下不能使用,因为您正在进行重定向。重定向意味着在特定 action/controller 处发出完整请求。 ViewBag 本质上仅用于在单个请求中将数据从操作传递到视图,这意味着进行重定向将擦除保存在 ViewBag 中的所有数据。在这种情况下,我认为唯一最好的方法是使用 TempData,因为即使进行了重定向,它也会保留数据,但是 当在同一控制器中进行重定向时 ,所以如果您重定向到另一个控制器,您最终会丢失在 TempData 对象中注册的数据。

我可以看到您正在尝试寻找一种方法来提醒用户注意不同的通知,但您可以看到我的回答 关于该方法的详细信息: