I want to upload and save a file along with other user input data having datatype int,string and datetime. I would like save the file to the hard-drive and save the path and other input data in the SQL Server database table. I am getting AggregateException whenever I am trying to do both together. I am new to ASP.NET MVC and Web API.
Below is my action method in ASP.NET MVC project.
public ActionResult AddOrEdit(mvcCandidate cn)
{
if (cn.ID == 0)
{
if (cn.cvFile.ContentLength != 0)
{
string filename = Path.GetFileNameWithoutExtension(cn.cvFile.FileName);
string extension = Path.GetExtension(cn.cvFile.FileName);
filename = filename + DateTime.Now.ToString("yymmssff") + extension;
cn.path = "~/Uploads/" + filename;
filename = Path.Combine(Server.MapPath("~/Uploads/"), filename);
cn.cvFile.SaveAs(filename);
}
else
cn.path = "";
try
{
HttpResponseMessage response = GlobalVariables.WebApiClient.PostAsJsonAsync("Candidates", cn).Result;
}
catch (AggregateException ex)
{
var ch = ex.Message;
return null;
}
}
}
And this is the action method in WebAPI project
public IHttpActionResult PostCandidate(Candidate candidate)
{
db.Candidates.Add(candidate);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = candidate.ID }, candidate);
}
The model class is as below:
public class mvcCandidate
{
public int ID { get; set; }
[Display(Name="Name")]
public string Name { get; set; }
[Display(Name = "Address")]
public string Adress { get; set; }
[Display(Name = "Date Of Birth")]
[DataType(DataType.Date)]
public Nullable<System.DateTime> DOB { get; set; }
public string PIN { get; set; }
public Nullable<int> CompanyID { get; set; }
[Display(Name = "CV")]
public string path { get; set; }
public HttpPostedFileBase cvFile { get; set; }
public virtual mvcCompany Company { get; set; }
}

PostAsJsonAsyncactually calls yourPostCandidatemethod?