【问题标题】:MVC Routing Issue - refreshing same pageMVC 路由问题 - 刷新同一页面
【发布时间】:2013-08-02 11:01:33
【问题描述】:

我有一个编辑页面,提交表单后,我会刷新页面,而不是将用户重定向到索引页面。为此,我将项目的 ID 保存在临时变量中,然后使用临时变量 ID 将用户重定向到编辑页面。像这样的:

[HttpGet]
public ActionResult Edit(Guid id)
{
    TempData["CategoryID"] = id;
    Category c = new CategoriesBL().GetCategory(id);
    return View(c);
}

[HttpPost]
public ActionResult Edit(Category c)
{
    new CategoriesBL().UpdateCategory(c);
    return RedirectToAction("Edit", (Guid)TempData["CategoryID"]);
}

这很好用。但是,我在同一页面上有两种不同形式的方法,每当我提交这两种方法中的任何一种时,重定向都不起作用,并且出现异常。

其中一种方法不起作用:

[HttpPost]
public ActionResult AddNewThumbnail()
{
    List<byte[]> thumbs = new List<byte[]>();

    for (int i = 0; i < Request.Files.Count; i++)
    {
        thumbs.Add(ConvertToByteArray(Request.Files[i].InputStream));
    }

    new CategoriesBL().AddCategoryThumbnail(thumbs, (Guid)TempData["CategoryID"]);
    return RedirectToAction("Edit", (Guid)TempData["CategoryID"]);
}

例外:

参数字典包含不可为空类型“System.Guid”的参数“id”的空条目....

我认为这是路由的问题,但事实是使用了相同的实现,并且它在一种形式上工作,而不是在另一种形式上工作。我不确定我是否做错了什么,或者是否有更好的方法来做到这一点。

注意:我已经多次调试了代码,并且我传递给方法的 ID 中确实有一个值。但是,当页面重新加载时,URL 没有 ID。

调试

问题似乎是由于我使用的表格不同。第一个表单我只是在编辑文本,它是这样的:

@using (Html.BeginForm()) {
    // ....
}

在第二种形式中,我正在保存和上传图片,因此形式必须不同

@using (Html.BeginForm("AddNewThumbnail", "Category", FormMethod.Post, new { enctype = "multipart/form-data" })) {
    // ....
}

不知何故,当我将表单更改为“正常”时,一切正常。但是我当然不能使用它,因为我想从这个表单中保存图像。

【问题讨论】:

  • 让我们通过GET 请求展示您的AddNewThumbnail()
  • 没有AddNewThumbnail()GET 请求。我唯一的GET 请求是Edit(Guid id) 方法。

标签: asp.net-mvc routing page-refresh


【解决方案1】:

传递您认为的价值。像这样的

[HttpPost]
public ActionResult Edit(Category c, FormCollection f)
{
   Guid categoryID =  (Guid)f["catergoryID"];
   new CategoriesBL().UpdateCategory(c);
   return RedirectToAction("Edit", catergoryID);
}

【讨论】:

  • Edit 方法的 Post 方法适用于 TempData。问题出在 AddNewThumbnail() 方法上。
  • 我尝试了您的建议,但仍然无法正常工作。这是一个奇怪的问题,我能找到的唯一原因是我正在使用的表单,但检索到的 ID 仍然不为空。
【解决方案2】:

在您的第一个示例中,您进行了初始化:

TempData["CategoryID"] = id;

GET 方法中。因此,您必须先初始化您的(Guid)TempData["CategoryID"],然后再尝试在此处访问它:

return RedirectToAction("Edit", (Guid)TempData["CategoryID"]);

【讨论】:

  • 正如我在调试代码时已经提到的,ID 不为空。这只是非常奇怪的行为。在AddNewThumbnail() 方法中的return RedirectToAction("Edit", (Guid)TempData["CategoryID"]); 之前,我将(Guid)TempData["CategoryID"] 保存为数据库中的ID,它不为空。
猜你喜欢
  • 2018-02-02
  • 2016-09-06
  • 1970-01-01
  • 2015-08-26
  • 2021-12-31
  • 2017-10-06
  • 1970-01-01
  • 2016-12-05
相关资源
最近更新 更多