c# - 将数据从一个表单传递到同一视图中另一个表单的操作方法
问题描述
我有一个AccountSetup.cshtml
用两种形式调用的类型化视图:
@model ViewModel
@using (Html.BeginForm())
{
// input form stuff
<input type="submit" id="Submit"" />
}
@using (Html.BeginForm())
{
// other input form stuff
<input type="button" onclick="location.href='@Url.Action("CreateAccount", "AccountSetup")'" />
}
第一种形式将数据发送到 this post 方法并且工作正常。但是,当我提交转到 Get 方法的第二个表单时,我丢失了模型数据。不会将TempData.Keep
所有帖子的所有数据保留回控制器吗?
[HttpPost]
public ActionResult AccountSetup(ViewModel AccountInfo)
{
TempData["AccountInfo"] = AccountInfo;
// writing to database
TempData.Keep("AccountInfo");
return View(AccountInfo);
}
[HttpGet]
public ActionResult CreateAccount(ViewModel AccountInfo)
{
if (TempData["AccountInfo"] != null)
{
// functionality
var data = TempData["AccountInfo"] as ViewModel
}
return View();
}
解决方案
每个请求(get/put/post)都完全独立于下一个请求(想象您的代码在服务器集群上运行),所以仅仅因为您将一些数据保存在“本地”,它不会在下一次调用时存在服务器(或集群中的其他服务器之一)。特定的 TempData 实例仅在“AccountSetup”期间存在。
如果您希望某些内容出现在 CreateAccount 的视图模型中,您将需要在您的视图中使用 @Html.HiddenFor 之类的东西。
但实际上,您可能只想在视图中存储“帐户 ID”并从数据库中重新加载实际数据,因为您不想“相信”客户端发送给您的任何内容,因为任何黑客都可以通过他们需要您的服务器的任何数据,因此您必须验证所有内容。
推荐阅读
- c# - Xamarin.Forms Android 将图像保存到设备库时获得访问被拒绝异常而未在设备中启用存储权限
- dart - Dart 编程语言中的自定义异常
- vuejs3 - 升级到 VueJs3 、 Vuex4 、 VueCli4.5 、 VueRouter4 后运行 vue 项目出现问题
- javascript - 如何在按钮单击时更改图表 js 数据
- swift - 错误 ITMS-90085:“二进制文件中没有架构
- gnome - 如何在 gjs 中使用“lang”?
- python - 如何将 python 多处理队列和进程与非常庞大的生成器一起使用?
- kubernetes - 如何防止重复的协调调用
- r - [[base R]] 添加T/F列是否为每组的最小值
- pyspark - 如何在 Databricks 笔记本中使用 Airflow 变量?