Home > database >  asp.net mvc file upload and data passing issues to controller
asp.net mvc file upload and data passing issues to controller

Time:04-07

I have following data in html table and trying to submit the data but I miss additional data from view to controller and I can only getting uploaded files details. how to pass file details and other data in each row simultaneously. Here I need to pass StudentName1 & StudentName2 along with corresponding file to controller.

<form action="" method="post" enctype="multipart/form-data">
    <div class='row'>
  <label for="txt">StudentName1:</label>
  <input type="text" name="name1" id="name1" />
  <label for="file1">Filename:</label>
  <input type="file" name="files" id="file1" />
  </div>


<div class='row'>
  <label for="txt">StudentName2:</label>
  <input type="text" name="name2" id="name2" />
  <label for="file2">Filename:</label>
  <input type="file" name="files" id="file2" />
</div>
  <input type="submit"  />
</form>

COntroller

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file in files) {
    if (file.ContentLength > 0) {
      var fileName = Path.GetFileName(file.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/Myuploads"), fileName);
      file.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
}

CodePudding user response:

You have to create model for student data or you can go with parameters as well.
Once you done with your model you just need to follow the steps from this link

CodePudding user response:

You can create a model class as follows

public class StudentInputObject
{
    [Required]
    public List<IformFile> files{ get; set; }

    [Required]
    public string StudentName { get; set; }

}

and pass it as a parameter to your post controller to keep the code more modular, or pass the student name as an additional parameter directly in the controller, like so

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files, string student_name) {
  foreach (var file in files) {
    ...
  }
  ...
}
  • Related