如何从MVC Controller更新后从Url隐藏状态查询字符串

时间:2013-08-12 11:17:59

标签: asp.net-mvc razor

我有一个根据特定ID显示信息的视图。

我的控制器是:

 public ActionResult ModifyWorkout(string WorkoutId, bool? Status)
    {
        Guid pkWorkoutId = new Guid(WorkoutId);
        BLLWorkouts _objBLLWorkouts = new BLLWorkouts();
        var WorkoutRow = _objBLLWorkouts.GetOneWorkout(pkWorkoutId);
        WorkoutModel PageModel = new WorkoutModel
        {
            pkWorkoutId = WorkoutRow.pkWorkoutId,
            WorkoutName = WorkoutRow.WorkoutName,
            WorkoutNote = WorkoutRow.WorkoutNote,
            Sessions = WorkoutRow.Sessions,
            CmpFlag = WorkoutRow.CmpFlag,
            tblWorkoutSessions = WorkoutRow.tblWorkoutSessions
        };
        ViewBag.UpdateStatus = Status;
        return View(PageModel);
    }

我总是将查询字符串作为Workout id传递以获取单个记录。但是当我更新那些记录时,它会发布到另一个动作:

 public ActionResult UpdateWorkout(WorkoutModel model)
    {
        bool _status = false;
        BLLWorkouts _objBLLWorkouts = new BLLWorkouts();
        tblWorkout _row = new tblWorkout();
        _row.WorkoutName = model.WorkoutName;
        _row.WorkoutNote = model.WorkoutNote;
        _row.Sessions = model.Sessions;
        _row.pkWorkoutId = model.pkWorkoutId;
        _row.CmpFlag = model.CmpFlag;
        _status = _objBLLWorkouts.UpdateWorkout(_row);

        return RedirectToAction("ModifyWorkout", new { WorkoutId = model.pkWorkoutId, Status = _status });

    }

现在的问题是,在更新我的网址后会变成这样:

/ModifyWorkout?WorkoutId=438b6828-1a21-4ad0-9e40-485dda75b1f6&Status=true"

由于Url中的&Status=true会刷新页面,因此即显示状态消息。

<div >
            @if (ViewBag.UpdateStatus != null)
            {
                if (ViewBag.UpdateStatus)
                {
                <span class="successmsgCommon">Workout updated successfully.</span>
                }
                else
                {
                <span class="errormsgCommon">Workout was not updated. Please try again.</span>
                }
            }

        </div>

有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

使用TempData发送值

  TempData["Status"] = true; 

消费

 if (TempData["Status"])

关于TempData

  • TempData用于将数据从当前请求传递到后续请求,意味着重定向。
  • TempData是一个字典对象,派生自TempDataDictionary类并存储在短命会话中

答案 1 :(得分:1)

您可以使用TempData:

TempData["Status"] = _status;
return RedirectToAction("ModifyWorkout", new { WorkoutId = model.pkWorkoutId });

ASP.NET MVC将为下一个请求存储此值,以便您可以在重定向的操作中读取它。

if ((bool)TempData["Status"])
{
    <span class="successmsgCommon">Workout updated successfully.</span>
}
else
{
    <span class="errormsgCommon">Workout was not updated. Please try again.</span>
}