Tell modelbinding that MVC action parameter is JSON

此生再无相见时 提交于 2019-12-11 14:22:18

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/19113384/tell-modelbinding-that-mvc-action-parameter-is-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!