在ASP.NET MVC中,当使用return View()
进行POST后,模型数据可能会丢失。这是因为return View()
方法会重新加载视图,并且不会将模型数据传递回视图。
为了解决这个问题,可以使用TempData
来临时保存模型数据,并在重新加载视图时将其传递回视图。
以下是一个解决方法的代码示例:
在控制器中:
[HttpPost]
public ActionResult YourAction(YourModel model)
{
if (ModelState.IsValid)
{
// 保存模型数据到TempData
TempData["YourModel"] = model;
// 执行其他操作(如保存到数据库等)
// 重定向到GET方法,显示视图
return RedirectToAction("YourAction");
}
// 如果模型验证失败,返回视图,并显示验证错误信息
return View(model);
}
[HttpGet]
public ActionResult YourAction()
{
// 从TempData中获取模型数据
YourModel model = TempData["YourModel"] as YourModel;
// 清除TempData中的模型数据
TempData.Remove("YourModel");
// 如果模型数据存在,将其传递回视图
if (model != null)
{
return View(model);
}
// 如果模型数据不存在,返回一个新的模型对象
return View(new YourModel());
}
在视图中:
@model YourNamespace.YourModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.Property1)
@Html.ValidationMessageFor(m => m.Property1)
}
通过在POST方法中使用TempData
来保存模型数据,然后在GET方法中从TempData
中获取并传递回视图,可以解决模型数据丢失的问题。