在控制器和窗体之间跳转时保留模型的 MVC



所以我最近在.net MVC中启动了项目,并且在保存数据时遇到了问题。我在某处读到,为了做到这一点,你必须来回传递模型。我尝试这样做,但它仍然遇到问题。在我的项目中,我现在有两个按钮,getData 和 getData2。我的视图打印它们的真/假值。当我按下一个时,它变成真,但如果我按下另一个,它变成真,但另一个变成假。我希望他们都保持真实,如果我按下他们两个。

控制器:

[HttpPost]
public ActionResult GetData(TestSite.Models.FarModels theFars)
{      
    theFars.HasData = true;
    return RedirectToAction("FarCalc",theFars);             
}
[HttpPost]
public ActionResult GetData2(TestSite.Models.FarModels theFars)
{
    theFars.HasData2 = true;
    return RedirectToAction("FarCalc", theFars);
}
[HttpGet]
public ActionResult FarCalc(TestSite.Models.FarModels theFars)
{                                
    return View(theFars);
}

视图:

@using (Html.BeginForm("GetData", "Home", FormMethod.Post))
   {
    //@Html.TextBoxFor(model => model.FarValue)
    <input type="submit" value="GetData" />
}
@using (Html.BeginForm("GetData2", "Home", FormMethod.Post))
{
    //@Html.TextBoxFor(model => model.FarValue)
    <input type="submit" value="GetData2" />
}
@Model.HasData
@Model.HasData2

谢谢

您需要使用 TempData 对象,因为使用 RedirectToAction 会返回状态代码 302,并且模型绑定不存在。 下面是一个很好的例子。

https://www.codeproject.com/Tips/842080/How-to-Persist-Data-with-TempData-in-MVC

最新更新