I have a very simple view that will prompt a user to select a JSON file and then parse it.
Here is the relevant code from the view...
@using (Html.BeginForm("AddSampleDataJSON", "Event"))
{
<input type="file" name="GetJSONFile" /><br>
<input type="submit" />
}
Here is the method from the controller:
[HttpPost]
public ActionResult AddSampleDataJSON(FormCollection form)
{
string path = ??
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
List<Event> events =
JsonConvert.DeserializeObject<List<Event>>(json);
}
return View();
}
The question then is how do I access the full path so I can send it to the StreamReader to eventually parse the JSON. I don't see it in the FormCollection object.
HttpPostedFileBase GetJSONFileand it will be populated with the file contents. And you need to set theenctype = "multipart/form-data"attribute in the form tag