1

I coded a "Product Create" page which saves a product to the database perfectly... Product has ID,CODE,NAME properties. Now I need to add Image as well.

My old code is below

[HttpPost]
public ActionResult ProductsCreate(ProductDetailViewModel prod_)
{
    if (ModelState.IsValid)
    {
       db.AY_PRODUCTS.Add(prod_.product);
       db.SaveChanges();
    }      
}

How should I change the View and Controller to save the Model with Image?

Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189
  • Is the image a property of product? Where are you getting the image from? Post your form as well. – Hjalmar Z Mar 26 '15 at 08:35
  • Have a look at my answer on http://stackoverflow.com/questions/9092723/preview-image-before-uploading-file/29036150#29036150 and let me know if it works or not... – Murat Yıldız Mar 26 '15 at 08:46

3 Answers3

5

Add property HttpPostedFileBase to your model. Use it in your view to post image.

public HttpPostedFileBase YourFile { get; set; }

In your action, save this image to your location.

In your View: remember enctype = "multipart/form-data" in your form.

<input name="YourFile" id="YourFile" type="file" accept="image/jpeg, image/png,image/jpg" value="">

Tips: Maybe this is no need for your problem. You should name the action just "Create". If i'm not wrong, you have ProductController, right? So you just need name this to Create, no need "ProductsCreate".

toannm
  • 485
  • 4
  • 9
3

Add this in model

[Display(Name = "Upload File")]
[DataType(DataType.Upload)]
public HttpPostedFileBase Image { get; set; }

In your view allow your form to post file by adding this enctype = "multipart/form-data"

@using (@Html.BeginForm("ActionName","ControllerName",FormMethod.Post,new { enctype = "multipart/form-data" }))
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
0

//in view

@using (Html.BeginForm("Create", "Banner", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
    @Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
    <input id="File1" name="File1" type="file" />
    @Html.ValidationMessageFor(model => model.ImagePath)
</div>
}

//in controller

[HttpPost]
    public ActionResult Create(tblBanner tblbanner)
    {
        if (ModelState.IsValid)
        {
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
            {
                tblbanner.ImagePath = clsUploadFile.uploadFile(Request.Files[0], "/Content/BannerImages/");
            }

            db.tblBanners.AddObject(tblbanner);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(tblbanner);
    }

// clsUploadFile defination is

public static class clsUploadFile
{
    public static string uploadFile(HttpPostedFileBase file, string UploadPath)
    {
        string imgPath = null;
        //var fileName = DateTime.Now.ToString();
        //fileName = fileName.Replace(" ", "_");
        //fileName = fileName.Replace("/", "_");
        //fileName = fileName.Replace(":", "_");
        string fileName = System.IO.Path.GetRandomFileName();
        fileName = fileName.Replace(".", "");
        var ext = System.IO.Path.GetExtension(file.FileName);
        fileName += ext;

        System.IO.DirectoryInfo dr = new System.IO.DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~" + UploadPath));
        System.IO.FileInfo[] files = dr.GetFiles();
        for(;true;)
        {
            if (!files.Where(o => o.Name.Equals(fileName)).Any())
                break;
            else
            {
                fileName = System.IO.Path.GetRandomFileName();
                fileName = fileName.Replace(".", "");
                fileName += ext;
            }
        }
        var path = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~" + UploadPath), fileName);
        file.SaveAs(path);
        imgPath = UploadPath + fileName;
        return imgPath;
    }

    public static bool DeleteFile(string path)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
        if (file.Exists)
        {
            file.Delete();
            return true;
        }
        else
            return false;
    }
}
vicky
  • 1,546
  • 1
  • 18
  • 35