如何处理包含路由参数的URL的POST请求?

时间:2022-06-30 11:21:25

I'm working on an ASP.NET MVC4 web app, and I have a controller method for handling a GET request with an id in the URL, like so ...

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

[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);
}

IN my view for this controller method, I have a form so that they can update it, that I want to POST back to the same URL. A URL like foo.com\items\1. Thats what the function above handles.

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

How do I make a function that handles a POST request for a function that requires a parameter, though? IN previous POST handlers I create a FormsCollection param, but when I add it to the param list for this function, the id param is null.

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

[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 });
}

Thank you!

谢谢!

1 个解决方案

#1


1  

You need to provide RouteValues in Html.BeginForm on your View:

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

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

#1


1  

You need to provide RouteValues in Html.BeginForm on your View:

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

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