I'm using a custom bootstrap, link: http://jasny.github.io/bootstrap/javascript.html#fileupload and I have a button to upload a file. This file is a JSON and I want to read it on my Controller. How can I do this? A method with a File Parameter and read this file using Json Parser.
Asked
Active
Viewed 4,461 times
2 Answers
3
Just create your form and create your action something like this:
using System.Web.Script.Serialization;
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
// get contents to string
string str = (new StreamReader(file.InputStream)).ReadToEnd();
// deserializes string into object
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(str);
// once it's an object, you can use do with it whatever you want
}
}

user1477388
- 20,790
- 32
- 144
- 264
-
I'm using a button to submit my file, but the parameter "file" is always null, why? @using (Html.BeginForm()){ } – Lücks Aug 20 '13 at 17:46
-
@Lücks It doesn't look like you are passing any variables in your form such as a file control. – user1477388 Aug 20 '13 at 17:50
-
I forgot to add a attribute "name" at my input file, now it works! Thanks! – Lücks Aug 20 '13 at 17:50
2
Look into a JSON parser. If you go here (http://theburningmonk.com/benchmarks/) and scroll down to JSON Serializers, you will see a list of popular serizalizers and their performance.
Depending on what you need out of the JSON, you can deserialize to dyanmic, and quite easily just access members of the object with .
operators. Your other option is to use http://json2csharp.com/ to generate a class file that matches the layout of the JSON and will allow you to deserialize into an exact object.
As for the uploading part, I suggest you take a look over here: File Upload ASP.NET MVC 3.0

Community
- 1
- 1

Pete Garafano
- 4,863
- 1
- 23
- 40