如何在 HttpPost 提交数据库更改后添加成功消息



我有一个添加到数据库中的HttpPost方法

public ActionResult SubmitData(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        var result = submitData(command);
        if (response.success)   
        {
            return RedirectToAction("MyHttpGetMethod");
        }
    }
    return View("MyHttpGetMethod", model);
}
public ActionResult MyHttpGetMethod(int Id)
{
    MyModel model = GetData(Id);
    return View(model);
}

调用HttpPost并成功进行数据库更改后,我重定向到HttpGet操作以获取更改后的当前数据。我喜欢显示成功消息在视图上。由于重定向,我无法使用 ViewBag,我无法使用 TempData,因为这里不建议使用它。

TempData 是此特定用例的有效解决方案。但是,如果您不喜欢这样做,则可以将查询字符串值从 HttpPost 操作传递到 GET 操作以指示事务的状态。

因此,更新您的 GET 操作以使用另一个参数

public ActionResult MyHttpGetMethod(int Id,string m="")
{
    MyModel model = GetData(Id);
    if(!String.IsNullOrEmpty(m) && m=="s")
    {
      // do some code to show the success message here.
      ViewBag.Msg="Saved Successfully";
    }
    return View(model);
}

然后在您的视图中,使用 ViewBag 项显示消息(使用您想要的任何样式)

<p>@ViewBag.Msg</p>

在您的 HttpPost 操作中,

return RedirectToAction("MyHttpGetMethod", new { id =model.Id, m="s"} );

最新更新