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?

2
  • Is the image a property of product? Where are you getting the image from? Post your form as well. Commented Mar 26, 2015 at 8:35
  • Have a look at my answer on stackoverflow.com/questions/9092723/… and let me know if it works or not... Commented Mar 26, 2015 at 8:46

3 Answers 3

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".

Sign up to request clarification or add additional context in comments.

1 Comment

how about the View part? What am I supposed to name the Image control?
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" }))

1 Comment

Correct answer. Very much plausible solution, also very easy and simple.
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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.