我想为上一次保存的下一次保存保留 2 个值。 MVC 4

I want to keep 2 values for next save from preivous save. MVC 4

用户输入 PWS(public 水系统)、LabID。然后单击保存按钮。 我希望这些值能够填充新的输入表单,该表单现在在成功保存时被清空。

@Html.TextBoxFor(model => model.PWS, new { @autofocus = "autofocus", @style="width:50px", @maxlength="5" }) 

控制器操作结果 第一次通过:

[HttpGet]
public ActionResult AddColiform(string sortorder)
{
    int batchid;
    batchid = Convert.ToInt32(Session["ThisBatch"]);
    //Session["ThisBatch"] = batchid;
    ViewBag.Methods = FillMethods();
    ViewBag.Latest = (from m in _db.BactiBucket
                      where m.Batch_ID == batchid
                      select m).ToList();
    ViewBag.ThisBatch = batchid;
    return View(new BactiBucket());
}

点击保存按钮时:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddColiform(BactiBucket bucket)
{
    if (ModelState.IsValid)
    {
        //FIRST RECORD SAVED FOR USER CREATES BATCH, OTHERWISE BATCH IS ZERO
        if (Session["ThisBatch"].Equals(0))
        {
            var newbatchid = CheckAndMakeBatchIfNone();
            Session["ThisBatch"] = newbatchid;
            bucket.Batch_ID = newbatchid;
        }
        _db.AddToBactiBucket(bucket);
        _db.SaveChanges();
        return RedirectToAction("AddColiform");
    }
    ViewBag.Methods = FillMethods();
    int batchid;
    batchid = Convert.ToInt32(Session["ThisBatch"]);
    ViewBag.ThisBatch = batchid;
    ViewBag.Latest = (from m in _db.BactiBucket
                      where m.Batch_ID == batchid
                      select m).ToList();
    return View(bucket);
}

好吧,如果那是一条蛇,它会咬我的。

在 ActionResult 的声明中,我将文本框的值传递给控制器​​。它带有 Post 动作。 (PWS 和 LabID 是输入的名称)。

[AcceptVerbs(HttpVerbs.Post)]
 public ActionResult AddColiform(BactiBucket bucket, string PWS, string LabID)

然后就在 return RedirectToAction("AddColiform");

之前

我为每个值设置会话变量: 会话["PWS"]=PWS; 会话["LabID"]=LabID;

当然我可能会使用 ViewBag.PWS 和 ViewBag.LabID

然后,在 return 构建新的添加记录表单时, 我恭敬地填充每个文本框的@Value:

@Html.TextBoxFor(model => model.PWS, new {@Value=Session["PWS"], @autofocus = "autofocus", @style="width:50px", @maxlength="5" })

@Html.TextBoxFor(model => model.LabID, new {@Value=Session["LabID"], @style="width:150px", @maxlength="20" })

因为我没有 运行 这个代码,所以我知道我必须检查 Session 对象是否不为空。或 ViewBag 对象。或者在第一次通过时将它们设置为“”。

我从 this forum thread

那里得到了这个

您可以在重定向中将额外的参数传递给您的 GET 方法,并使用这些值来设置模型的属性(请注意,不清楚为什么您的方法有一个参数 string sortorder 而您却从不使用它)

[HttpGet]
public ActionResult AddColiform(string sortorder, string PWS, string LabID)
{
  ....
  BactiBucket model = new BactiBucket() { PWS = PWS, LabID = LabID };
  return View(model);
}

[HttpPost]
public ActionResult AddColiform(BactiBucket bucket)
{
  if (ModelState.IsValid)
  {
    ....
    return RedirectToAction("AddColiform", new { PWS = bucket.PWS, LabID = bucket.LabID });
  }
  ....
}