【问题标题】:How to handle a POST request to a URL that contains route parameters?如何处理对包含路由参数的 URL 的 POST 请求?
【发布时间】:2013-05-14 20:17:50
【问题描述】:

我正在开发一个 ASP.NET MVC4 Web 应用程序,并且我有一个控制器方法来处理 URL 中带有 idGET 请求,就像这样......

[PortalAuthorization]
public ActionResult View(int id)
{
    // get the individual ftp log
    PortalFTPLog log = PortalFTPLogs.Get(id);

    if (log == null)
    {
        TempData["Error"] = "The provided ftp log id does not exist.";
        return RedirectToAction("Index");
    }

    // get the available matters to tie uploads to
    ViewBag.matters = PortalMatters.Get();

    return View(log);
}

在我对这个控制器方法的看法中,我有一个表单以便他们可以更新它,我想POST 回到相同的 URL。像 foo.com\items\1 这样的 URL。上面的函数就是这么处理的。

但是,如何创建一个函数来处理需要参数的函数的 POST 请求?在之前的 POST 处理程序中,我创建了一个 FormsCollection 参数,但是当我将它添加到此函数的参数列表中时,id 参数为空。

[HttpPost]
[PortalAuthorization]
public ActionResult View(FormCollection collection, int id)
{
    PortalFTPLog log = PortalFTPLogs.Get(id);

    if (log == null)
    {
        TempData["Error"] = "The provided ftp log id does not exist.";
        return RedirectToAction("Index");
    }

    // update the matter id and save to database
    log.Matter = Convert.ToInt32(collection.Get("matter"));
    log.Save();

    TempData["Notice"] = "The FTP log meta data has been updated.";

    return RedirectToAction("View", new { id = id });
}

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    您需要在您的 View 上的 Html.BeginForm 中提供 RouteValues:

     @using (Html.BeginForm(new {id = someIntIdValue}))
     {
         // Your form code  
     }
    

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 1970-01-01
      • 2017-04-02
      • 2011-04-30
      • 2014-04-02
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多