I have a Controller method that needs to accept multipart/form-data
sent by the client as a POST request. The form data has 2 parts to it. One is an object serialized to application/json
and the other part is a photo file sent as application/octet-stream
. I have a method on my controller like this:
[AcceptVerbs(HttpVerbs.Post)]
void ActionResult Photos(PostItem post)
{
}
I can get the file via Request.File
without problem here.However the PostItem is null.
Not sure why? Any ideas
Controller Code:
/// <summary>
/// FeedsController
/// </summary>
public class FeedsController : FeedsBaseController
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Photos(FeedItem feedItem)
{
//Here the feedItem is always null. However Request.Files[0] gives me the file I need
var processor = new ActivityFeedsProcessor();
processor.ProcessFeed(feedItem, Request.Files[0]);
SetResponseCode(System.Net.HttpStatusCode.OK);
return new EmptyResult();
}
}
The client request on the wire looks like this:
{User Agent stuff}
Content-Type: multipart/form-data; boundary=8cdb3c15d07d36a
--8cdb3c15d07d36a
Content-Disposition: form-data; name="feedItem"
Content-Type: text/xml
{"UserId":1234567,"GroupId":123456,"PostType":"photos",
"PublishTo":"store","CreatedTime":"2011-03-19 03:22:39Z"}
--8cdb3c15d07d36a
Content-Disposition: file; filename="testFile.txt"
ContentType: application/octet-stream
{bytes here. Removed for brevity}
--8cdb3c15d07d36a--
As @Sergi say, add HttpPostedFileBase file parameter to your action and I don't know for MVC3 but for 1 and 2 you have to specify in the form/view that you will post multipart/form-data like this :
And this is in my controller :
Hope it helps!
What does the
FeedItem
class look like? For what I see in the post info it should look something like:Otherwise it will not be bound. You could try and change the action signature and see if this works:
You could even try and add a
HttpPostedFileBase
parameter to your action:And if you're really feeling wild and naughty, add
HttpPostedFileBase
toFeedItem
:This last code snippet is probably what you want to end up with, but the step-by-step breakdown might help you along.
This answer might help you along in de right direction as well: ASP.NET MVC passing Model *together* with files back to controller