Monday, June 30, 2014

MVC - Saving Files AND Json Model

When posting files in MVC using AJAX, Microsoft gives us a great tool, the Request.Files collection. However, when passing files via ajax, MVC ignores your json model that you pass as well. You can see the way around this in the code snippets below.



And in our javascript, using jQuery's ajax() method...




I add the json model to the FormData collection. Once that's done, I can pull it from the Request.Form[] Name Value collection when it posts to the server.

WebApi and OData - Without Entity Framework

OData is pretty nice, all said. Makes displaying data in a grid way easier. Microsoft has done some pretty cool things with WebAPI, gotten rid of the last bits of weirdness that remain in MVC (imo). However, their odata implementation adds more typical MS weirdness...

While most oData parameters just "work" and apply directly to your IQueryable, unfortunately $inlinecount isn't one of them.
Fortunately there's a pretty easy workaround.

 Add WebApi and oData using NuGet.
Do this to your method.


The key to this is returning the OData PageResult. It's pretty neat that MS' oData implementation will just work on your IQueryable, without modification. It's just that WebAPI won't return a PageResult when it sees the $inlinecount parameter, like it will when you use an oData controller. My issue with the oData controller is that it forces you into exposing your entire model for each object in your graph. I'm not trying to expose all of my data, I'm just trying to get an easy oData endpoint to feed my sites. Rarely do I need to expose my entire object graph to the user, and those queries are way too heavy. I also don't want a lot of JS baggage by filtering and selecting only the properties I need. This solution works much better for me.

Tuesday, June 17, 2014

File and JSON Post in MVC

It seems strange to me that MVC doesn't handle posting a file and a model at the same time from AJAX by default. It'd be great if you could just send your data and "poof" it's all there for you. It doesn't seem to be, so I'll put down what I've found that works for me.

You create a javascript FormData object. Add your model (with property "model") and your file('s). Post as normal.

In your action method, remove any model parameter you had. You won't need it. Just look at the Request.Form["model"] and deserialize your json. Get your files in the Request.Form collection.