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?

1
  • 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. stackoverflow.com/help/how-to-ask Commented May 9, 2016 at 0:49

1 Answer 1

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)

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

2 Comments

@ Amin, The answer was self explanatory. You have made my life easier. Kudos to you. Many thanks.
@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 can be helpful

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.