简体   繁体   中英

Display uploaded data to MVC view and import selected record to database

I need to import user uploaded CSV data to database. Steps - 1. User upload data to MVC View 2. Display all uploaded data in the View 3. User can select the column name based on imported value 3. Import data based on user selection of the records.

To implement this, I created below Model -

public class ImportCSVData
{      
    public IEnumerable<System.Web.Mvc.SelectListItem> Names { get; set;}    // This is to display dynamic column      
    public HttpPostedFileBase File { get; set; }     
    public DataTable Data { get; set; }  
}  

In the controller, I am parsing the uploaded file (sample code)

    public ActionResult ImportCSVCustomer()
    {
        ImportCSVData model = new ImportCSVData();
        HttpPostedFileBase upfile = Request.Files["File"];
        model.File = upfile;            
            var dt = ParseCSVData(model);
            if (dt != null && dt.Rows.Count > 0)
            {                 
                var dcRec = new DataColumn("ShouldImport", typeof(bool));                 
                dcRec.DefaultValue = false;
                dt.Columns.Add(dcRec);         
                model.Data = dt;
                List<SelectListItem> Names = getColumnNames();
                model.Names = Names;                 
                return PartialView("_ImportedCSVCustomer", model);
            }                      
        return View();
    }

Sample View that I designed -

   @for (int i = 0; i < Model.Data.Rows.Count; i++)
   {
   <tr>
    <td data-val="@i">
    <input type="checkbox" name="sid" value=@Model.Data.Rows[i][Model.Data.Columns.Count - 1] class="sid">
   </td>
    @for (int j = 0; j < Model.Data.Columns.Count - 1; j++)
    {
     <td>
         @Model.Data.Rows[i][j].ToString()
         @Html.HiddenFor(Model.Data.Rows[i][j].ToString())
     </td>
     }
   </tr>
   }

I was working on the view to display, but , unable to get the model value after posting from View to Controller. Any idea how to implement this?

You need to pass the model in the return statement. So you need:

return View(model)

Then in the view you have to make sure you are implementing that view by having at the top of the .cshtml file

@model xxx.ImportCSVData

Where xxx is the namespace.

In all honest, I'd also put [HttpPost] on top of the controller as well to make sure you can only POST to it and I'd use the AntiForgeryToken. http://peterkellner.net/2014/05/19/asp-net-mvc-forms-need-include-html-antiforgerytoken-security/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM