.Net Asp.Net MVC C# Development

Saving/uploading files through form and creating XML in database

Model Definations:
public HttpPostedFileBase[] files { get; set; }


View:
@using (Html.BeginForm("newBen1", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
        <div class="col-md-4">
            @Html.LabelFor(model => model.ben.ben_supp_docs, htmlAttributes: new { @class = "control-label" })

            @Html.TextBoxFor(model => model.files, new { type = "file", @multiple = "multiple" })
            @Html.ValidationMessageFor(model => model.ben.ben_supp_docs, "", new { @class = "text-danger" })
        </div>
    </div>
}


Post Action Method:
[HttpPost]
        public ActionResult newben1(SuperModel model){
if (model.files[0] != null)
{
  if (!System.IO.Directory.Exists(Server.MapPath("~/UploadedFiles")))  //creating a new directory if not exists
     {                 System.IO.Directory.CreateDirectory(Server.MapPath("~/UploadedFiles"));
      }
 XElement[] xes = new XElement[10];

var xel = new XElement("Roots",
                            from files in model.files
                            select new XElement("RootFiles",
                            new XElement("File", new XAttribute("path", "~/UploadedFiles/Beneficiaries/" + ab1 + "/" + bid + "/"), new XAttribute("file", files.FileName)
                            )));   //creating the xml file structure with data in it

foreach (HttpPostedFileBase str in model.files)
  {
      var filename = Path.GetFileName(str.FileName);
      var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/Beneficiaries/" + ab1 + "/" + bid + "/") + filename);
      str.SaveAs(ServerSavePath);     // copying the files in the uploaded folder
    }
    model.ben.ben_supp_docs = xel.ToString(); //saving the list of file names and path in the database
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *