In this sample we are going to take a different approach to importing data from the traditional file upload method. This sample has a textarea and a button. Users will open their .csv or .txt file, copy the contents, paste them into the textarea, and submit.
Setting up the form
This part is pretty basic:
<textarea id="bulkcsvlist" name="bulkcsvlist" rows="20" cols="105"></textarea> <input type="submit" value="Upload File" />
Create import method
This sample shows the basics of parsing and adding the records, which assumes is uploading into a Contact table, with the first two fields in the row being FirstName and LastName respectively. You probably want to bake in your security checks and data validation.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadAll(FormCollection f)
{
string bulkcsvlist = f["bulkcsvlist"].ToString();
//
// Split the rows into an array
//
string[] rows = bulkcsvlist.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < rows.Length; i++)
{
//
// Split the tab separated fields (comma separated split commented)
//
//string[] dr = rows[i].Split(new char[] {','});
string[] dr = rows[i].Split(new char[] { '\t' });
//
// Add Contact for current row
//
if (dr.Length > 0)
{
Contact c = new Contact();
c.FirstName = dr[0].ToString();
c.LastName = dr[1].ToString();
c.CreateAndFlush();
c = null;
}
}
}
Normally I’ll throw each successful add into a List<> so whoever is uploading can validate the records look right or do any post-upload polishing, and the errors into a ViewData to display so the user can fix whatever needs fixing.
If you want a working sample, let me know!
