简体   繁体   中英

POSTing to an action with files and a parameter in ASP.NET MVC3

This is a follow-up question to ASP.NET MVC 3 - File Upload . I have a URL syntax that I cannot change. I need to upload files to a URL in the syntax of "/person/{personID}/files". Currently, I am trying the following:

index.html

<form action="/person/2/files" method="post" enctype="multipart/form-data">
    <div>Please choose a file to upload.</div>
    <div><input id="fileUpload" type="file" /></div>

    <div><input type="submit" value="upload" /></div>
</form>

The personID parameter value is dynamically populated when the form loads. Regardless, when I click "upload", I'm posting back to the following action:

UploadController.cs

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID)
{
  foreach (string file in Request.Files)
  {
    // Request.Files is empty
  }

  return View();
}

How do I POST both a collection of files AND a parameter using the URL syntax of "/person/{personID}/files"? I know this is a very specific request. I have run out of time on my project and I'm totally confused why the approach I'm using doesn't work. Can somebody please help me?

Thank you so very much.

Assuming you have a route defined for this custom url:

routes.MapRoute(
    "Upload",
    "person/{uniqueid}/files",
    new { controller = "Upload", action = "UploadFile" }
);

you just need to give your file input a name:

<div><input id="fileUpload" type="file" name="file" /></div>

Also I would recommend you to use action arguments instead of looping through Request.Files :

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID, HttpPostedFileBase file)
{
    return View();
}

and if you wanted to post multiple files:

<div><input type="file" name="files" /></div>
<div><input type="file" name="files" /></div>
<div><input type="file" name="files" /></div>
...

use a collection:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID, IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

You might also find the following blog post useful.

Or even better, use a view model:

public class MyViewModel
{
    public int UniqueID { get; set; }
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}

and then:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(MyViewModel model)
{
    return View();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM