I have no idea why I am getting this exception. I am trying to implement a simple upload image functionality.
I am getting the error when I am trying to save the image along with the rest of the data.
I suspect the the problem is in the view
, because I used this code from my model
and action
method in another project and the code worked.
Can someone help with this. I believe I am close.
Model :
public class Company
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CompanyId { get; set; }
public byte[] ImageData { get; set; }
[NotMapped]
public HttpPostedFileBase UploadImage { get; set; }
[NotMapped]
public string ImageBase64 => System.Convert.ToBase64String(ImageData);
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCountry { get; set; }
public string CompanyCity { get; set; }
public string CompanyPostalCode { get; set; }
public string CompanyPhoneNumber { get; set; }
public string CAId { get; set; }
}
Controller :
public ActionResult Create([Bind(Include = "CompId,ImageData,CompanyName,CompanyAddress,CompanyCountry,CompanyCity,CompanyPostalCode,CompanyPhoneNumber,EmailCA")] Company company, HttpPostedFileBase UploadImage)
{
if (ModelState.IsValid)
{
byte[] buf = new byte[UploadImage.ContentLength];
UploadImage.InputStream.Read(buf, 0, buf.Length);
company.ImageData = buf;
db.Companies.Add(company);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(company);
}
View :
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Company</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ImageData, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-10">
@Html.TextBoxFor(model => model.ImageData, new { type = "file" })
@*<input type="file" name="ImageData" class="input-files" />*@
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CompanyName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CompanyName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CAId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CAId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CAId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>