Reputation: 53
I am creating an ASP.NET MVC application and I am trying to save an image into my database that would be attached to a car so I can display it later. When I run my code I am able to create a new car and I save the image into a folder but no information is added to the database for the image table.
This is my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(HttpPostedFileBase[] files, [Bind(Include = "CarID,Year,Color,Mileage,Cost,MarketValue,BodyType,Drive,Notes,Available,VinNumber,CarLotID,ModelID")] Car car)
{
if (ModelState.IsValid)
{
foreach (HttpPostedFileBase file in files)
{
//Checking file is available to save.
if (file != null)
{
var InputFileName = Path.GetFileName(file.FileName);
var ServerSavePath = Path.Combine(Server.MapPath("~/CarImages/") + InputFileName);
//Save file to server folder
file.SaveAs(ServerSavePath);
var image = new Image()
{
ImagePath = ServerSavePath,
Title = ServerSavePath
};
car.Images.Add(image);
//assigning file uploaded status to ViewBag for showing message to user.
ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";
}
}
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MakeID = new SelectList(db.Makes, "MakeID", "Name", car.Model?.MakeID);
ViewBag.ModelID = new SelectList(db.Models, "ModelID", "Name", car.ModelID);
ViewBag.CarLotID = new SelectList(db.CarLots, "CarLotID", "LotName", car.CarLotID);
return View(car);
}
This is my model class for Image
:
public partial class Image
{
public int ImageID { get; set; }
public int CarID { get; set; }
public string Title { get; set; }
public string ImagePath { get; set; }
public HttpPostedFileBase ImageFile { get; set; }
public virtual Car Car { get; set; }
}
This is my model class for Car
:
using System;
using System.Collections.Generic;
using System.ComponentModel;
public partial class Car
{
public int CarID { get; set; }
public string Year { get; set; }
public string Color { get; set; }
public string Mileage { get; set; }
public decimal Cost { get; set; }
public string BodyType { get; set; }
public string Drive { get; set; }
public string Notes { get; set; }
public bool Available { get; set; }
public string VinNumber { get; set; }
public int CarLotID { get; set; }
public int ModelID { get; set; }
public virtual ICollection<Image> Images { get; set; }
public virtual CarLot CarLot { get; set; }
public HttpPostedFileBase[] files { get; set; }
}
This is my View
@model IgnitionHub2._0.Models.Car
@using IgnitionHub2._0.Models
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Car", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Car</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Year, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Year, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.files, "Add an Image", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
@Html.ValidationMessageFor(model => model.files, "", 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>
}
I deleted most of the dropdowns form the view for the post so it wouldn't be extra long.
Please help! Thank you!
Upvotes: 0
Views: 97
Reputation: 36595
Here is a working demo like below:
Model:
public partial class Car
{
public Car()
{
Images = new List<Image>() { };
}
public int CarID { get; set; }
public string Year { get; set; }
public string Color { get; set; }
public string Mileage { get; set; }
public decimal Cost { get; set; }
public string BodyType { get; set; }
public string Drive { get; set; }
public string Notes { get; set; }
public bool Available { get; set; }
public string VinNumber { get; set; }
public int CarLotID { get; set; }
public int ModelID { get; set; }
public virtual List<Image> Images { get; set; }
public HttpPostedFileBase[] files { get; set; }
}
public partial class Image
{
public int ImageID { get; set; }
public int CarID { get; set; }
public string Title { get; set; }
public string ImagePath { get; set; }
public virtual Car Car { get; set; }
public HttpPostedFileBase[] files { get; set; }
}
View:
@model Car
@using WebApplication2.Models
<h2>Create</h2>
@using (Html.BeginForm("Create", "Cars", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Car</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Year, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Year, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.files, "Add an Image", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
@Html.ValidationMessageFor(model => model.files, "", 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>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(HttpPostedFileBase[] files, Car car)
{
if (ModelState.IsValid)
{
foreach (HttpPostedFileBase file in files)
{
//Checking file is available to save.
if (file != null)
{
var InputFileName = Path.GetFileName(file.FileName);
var ServerSavePath = Path.Combine(Server.MapPath("~/CarImages/") , InputFileName);
//Save file to server folder
file.SaveAs(ServerSavePath);
var image = new Image()
{
ImagePath = ServerSavePath,
Title = ServerSavePath
};
//db.Images.Add(image);
// db.SaveChanges();
car.Images.Add(image);
//assigning file uploaded status to ViewBag for showing message to user.
ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";
}
}
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
Result:
Upvotes: 2
Reputation: 125
If you are going to keep the picture in a directory, just keep the path of the picture in the database. To store the image in the binary database, your Image model/Entity should be as follows.
To store the image in the binary database, your Image model should be as follows. You must translate the image you received in the control to byte array and assign it to the ImageFile variable.
Change your controler:
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
image.ImageFile = data
car.Images.Add(image);
Your Model:
public partial class Image
{
public int ImageID { get; set; }
public int CarID { get; set; }
public string Title { get; set; }
public string ImagePath { get; set; }
public byte[] ImageFile { get; set; }
public virtual Car Car { get; set; }
}
Upvotes: 2