【问题标题】:MVC Preserving Model When Jumping Between Controller and Forms在控制器和表单之间跳转时 MVC 保留模型
【发布时间】:2017-05-21 16:48:54
【问题描述】:

所以我最近在 .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

谢谢

【问题讨论】:

    标签: model-view-controller controller models


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 2017-06-10
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 2011-05-30
      相关资源
      最近更新 更多