0

I am new to ASP.NET MVC, so kindly excuse for mistakes.

I need a view page (index.cshtml) where I can display the image, change/delete the image by storing it in Varbinary(max) column in a SQL Server table.

There are these columns in the database table:

ID int  primary key Identity not null,
ImageName  nvarchar(50) ,
ImagePicInBytes varbinary(MAX) null

I am using a Image.cs with this code:

public class Image
{
    public int ID {get; set;}
    public string ImageName {get; set;}
    public byte[] ImagePicInBytes {get; set;}
}

ImageContext class as below

public class ImageContext : DbContext
{
    public DbSet<Image> Images { get; set; }
}

Connection string as below

<connectionStrings>
    <add name="ImageContext"  
         connectionString="server=.; database=Sample; integrated security =SSPI" 
         providerName="System.Data.SqlClient"/>
</connectionStrings>

ImageController as below

public class ImageController : Controller
{
    private ImageContext db = new ImageContext();

    // GET: /Image/
    public ActionResult Index()
    {
        return View(db.Images.ToList());
    }

    // GET: /Image/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Image image = db.Images.Find(id);

        if (image == null)
        {
            return HttpNotFound();
        }

        return View(image);
    }
}

Have created views as below

public class ImageController : Controller
{

        private ImageContext db = new ImageContext();

        // GET: /Image/
        public ActionResult Index()
        {
            return View(db.Images.ToList());
        }


        // GET: /Image/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Image image = db.Images.Find(id);
            if (image == null)
            {
                return HttpNotFound();
            }
            return View(image);
        }

        // GET: /Image/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Image image = db.Images.Find(id);
            if (image == null)
            {
                return HttpNotFound();
            }
            return View(image);
        }

        // POST: /Image/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Image image = db.Images.Find(id);
            db.Images.Remove(image);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

    }
}

My create.cshtml (view) as below

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ImageName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ImagePicInBytes)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ImageName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ImagePicInBytes)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

I have the below 3 questions

  1. How can I create a new record in datatable by uploading new image from file system to Varbinary column in database?

  2. How can I have the view to have FILEUPLOAD control in the 'create View' and 'Edit view'

  3. Can I use HttpPostedFileBase to achieve the above from Create.cshtml? If yes: how? Any suggestions or reference links available?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ismail Khan
  • 1
  • 1
  • 2
  • I think you need to break this question into smaller more easily identifiable problems. You should post questions with a single issue and the smallest amount of code that can reproduce the issue. http://stackoverflow.com/help/how-to-ask – Mick May 09 '16 at 00:49

1 Answers1

3

first of all create a viewmodel for Image class

   public class ImageViewModel
   {
    public string ImageName {get; set;}
    public HttpPostedFileBase ImagePic {get; set;}
   }

then for uploading a photo in your create view

@model ExmpleProject.Models.ImageViewModel

@using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new {enctype="multipart/form-data"})){ 

         @Html.AntiForgeryToken() 
         @Html.LabelFor(m => m.ImageName)
         @Html.TextBoxFor(m => m.ImageName)

         @Html.LabelFor(m => m.ImagePic )
         @Html.TextBoxFor(m => m.ImagePic , new { type = "file" })
         <br />
         <input type="submit" name="Submit" id="Submit" value="Upload" />
    }

then in post method of your controller for create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageViewModel model)
{
    if (ModelState.IsValid)
    {
       var uploadedFile = (model.ImagePic != null && model.ImagePic.ContentLength > 0) ? new byte[model.ImagePic.InputStream.Length] : null;
                if (uploadedFile != null)
                {
                    model.ImagePic.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
                }
        Image image = new Image
        {
            ImageName = model.ImageName,
            ImagePicInBytes = uploadedFile
        }
        db.Create(image);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(model);
}

so for your edit method you can do similar implementation but instead of Create(image) use Update(image)

Amin K
  • 106
  • 1
  • 10
  • @ Amin, The answer was self explanatory. You have made my life easier. Kudos to you. Many thanks. – Ismail Khan May 09 '16 at 18:07
  • @IsmailKhan glad to help, actually this was part of my approach for creating a register wizard form in mvc with more advances,if you are doing such a thing, this [link](http://stackoverflow.com/questions/36679403/implementing-jquery-ajax-in-multi-step-register-forms-based-on-splited-viewmodel/36873986#36873986) can be helpful – Amin K May 09 '16 at 18:22