0

I am using an upload control to send a file to a JsonResult, but I am also sending up a JSON string as a second parameter. This is all getting posted with the Content-Type:multipart/form-data;

[HttpPost]
public JsonResult UploadDocument(HttpPostedFileBase file, DocumentViewModel model)
{ ... }

I know MVC is capable of binding directly to a viewmodel if the content type is set to application/json but I don't think it's possible for me to set that in this case.

Is there any way for me to get MVC to automatically bind my posted json string to model?

4imble
  • 13,979
  • 15
  • 70
  • 125

2 Answers2

2

That's not possible out-of-the-box. You will have to manually deserialize the JSON string parameter that you would read from the request to your view model inside the controller action or write a custom model binder for it that will do the job. Ideally you shouldn't be posting the model data as a JSON string but rather respect the content type you specified : multipart/form-data. So the correct way to handle this scenario is to modify the client code that is sending the request in order to respect the content type.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Figured as much, I think I'll go with the custom model binder. Just wanted to check I wasn't reinventing the wheel. Many thanks. – 4imble Oct 01 '13 at 10:21
  • 1
    Well, actually you will be reinventing the wheel because you will be writing custom deserializers for something that could be handled properly at protocol level if your client simply respected the content type it is pretending to be sending: `multipart/form-data`. But if you have no control over this poorly written client side code, then I am afraid that this is the way to go. – Darin Dimitrov Oct 01 '13 at 10:23
0

As I was unable to change the content-type I found this blog to be exactly what i needed.

"... our whole request stream(data) won’t be json string. Only the guest parameter will be supplied as json string..."

http://ishwor.cyberbudsonline.com/2012/07/fun-with-aspnet-mvc-3-custom-json-model-binder.html

4imble
  • 13,979
  • 15
  • 70
  • 125