首页 > 解决方案 > 将数据从一个表单传递到同一视图中另一个表单的操作方法

问题描述

我有一个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();
}

标签: c#asp.net-mvc

解决方案


每个请求(get/put/post)都完全独立于下一个请求(想象您的代码在服务器集群上运行),所以仅仅因为您将一些数据保存在“本地”,它不会在下一次调用时存在服务器(或集群中的其他服务器之一)。特定的 TempData 实例仅在“AccountSetup”期间存在。

如果您希望某些内容出现在 CreateAccount 的视图模型中,您将需要在您的视图中使用 @Html.HiddenFor 之类的东西。

但实际上,您可能只想在视图中存储“帐户 ID”并从数据库中重新加载实际数据,因为您不想“相信”客户端发送给您的任何内容,因为任何黑客都可以通过他们需要您的服务器的任何数据,因此您必须验证所有内容。


推荐阅读