how to asp net core MVC crud operations with image consume from web ApI

jewel 1,186 Reputation points
2025-06-21T06:28:07.7966667+00:00

I want to see the image from the API in the view of the MVC application. But I can't see it. And I want to Insert, update the image from the MVC view. How to do this. If the experts could help, I would be benefited.

//Api Code

 [HttpGet("Getproductrecord")]
 public IActionResult GetProductRecord()
 {
     var data =  _context.tbl_Products.ToList();
                 
     return Ok(data);
 }
  private string uplodadimage( tbl_product model)
  {
      string uniquefilename = string.Empty;
      if (model.imagepath != null)
      {
          string uploadfolder = Path.Combine(Directory.GetCurrentDirectory(), "Contain/Image/");
          uniquefilename = model.productname + "_" + Guid.NewGuid().ToString() + "_" + model.imagepath.FileName;
          string filepath = Path.Combine(uploadfolder, uniquefilename);
          using (var fileStream = new FileStream(filepath, FileMode.Create))
          {
              model.imagepath.CopyTo(fileStream);
          }
      }
      return uniquefilename;
  }
  [HttpPost("Inserprodcut")]
  public IActionResult insertrecord( tbl_product model)
  {
      try
      {
          string uniquefilename = uplodadimage(model);
          var data = new tbl_product()
          {
           
              productname = model.productname,
            Path = uniquefilename,
          };
          _context.tbl_Products.Add(data);
          _context.SaveChanges();
        
      }
      catch (Exception ex)
      {
          return BadRequest("Data Not Saved");
      }
      return Ok("Data Added successfully");
  }
  [HttpPut("Productupdate")]
  public IActionResult Updatedata(tbl_product np)
  {
          var data = _context.tbl_Products.Where(e => e.productID == np.productID).SingleOrDefault();
    string uniquefilename = string.Empty;
          data.productname = np.productname;
      
          uniquefilename = uplodadimage(np);
          data.Path = uniquefilename;
          _context.tbl_Products.Update(data);
          _context.SaveChanges();
      return Ok(data); 
  }
//Mvc View
 
function GetList() {
    
     $.ajax({
         url: "/Product/GetProductRecord",
         type: 'Get',
         datatype: 'json',
         success: function (data) {
              $('#myTable tbody').empty();
        $.each(data, function (i, item) {
        var rows = "<tr>" +
           
             "<td date-lable='Prodcut Name'>" + item.productname + "</td>"
            + "<td date-lable='Image'><img  class='rsponsimage' src=' C:/Users/user/source/repos/Myapiwithmvc7_6_25/Contain/Image/" + item.path + "'  alt=''></td>"
            + "<td style='text-align: center;' date-lable='Action'><a  href='#' onclick='editpro(" + item.productID + ")'><i class='bx bxs-edit' style='color:#1484fb' ></i></a>&nbsp<a  href='#' onclick='DeleteRecord(" + item.productID + ")'><i class='bx bx-reset'></i></a></td>"
            + "</tr>";
        $('#myTable tbody').append(rows);
    });
          
        }
    });
}

//Mvc
//Image Not Display
  public JsonResult GetProductRecord()
  {
      List<productvm> Data = new List<productvm>();
      HttpResponseMessage response = _Client.GetAsync(_Client.BaseAddress + "/Product/Getproductrecord").Result;
      if (response.IsSuccessStatusCode)
      {
          string result = response.Content.ReadAsStringAsync().Result;
          Data = JsonConvert.DeserializeObject<List<productvm>>(result);
      };
     
      return Json(Data);
  }


  public IActionResult Updatedata(tbl_product model)
  {
      string data = JsonConvert.SerializeObject(model);
      StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
      HttpResponseMessage respons = _Client.PutAsync(_Client.BaseAddress+ "/Product/Productupdate" , content).Result;
      if (respons.IsSuccessStatusCode)
      {
          return RedirectToAction("index");
      };
      return RedirectToAction("index");
  }
Developer technologies ASP.NET ASP.NET API
0 comments No comments
{count} votes

Accepted answer
  1. Marcin Policht 49,640 Reputation points MVP Volunteer Moderator
    2025-06-21T11:07:04.9066667+00:00

    Looks like there are a few issues in your code:

    1. Image not displaying

    The following is a local path on the server, which won't work in the browser.

    src='C:/Users/user/source/repos/Myapiwithmvc7_6_25/Contain/Image/" + item.path
    

    You need to serve the uploaded images as static files from the API and reference them using a public URL.

    a) Serve Static Files from the API:

    In your API project:

    Startup.cs / Program.cs

    app.UseStaticFiles(); // Make sure this is added
    

    Inside wwwroot Folder (recommended) Move your images to wwwroot/images.

    Modify your upload path:

    string uploadfolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/");
    

    Update returned path:

    return "/images/" + uniquefilename; // relative URL to be used in img src
    

    b) Correct image path in view:

    Update your JavaScript:

    "<td data-label='Image'><img class='rsponsimage' src='" + item.path + "' alt='' /></td>"
    

    If you return just file name (item.path = "image.jpg"), then:

    src='https://yourapiurl/images/" + item.path + "'
    
    1. Inserting image from MVC view

    Your API is expecting multipart/form-data for image upload, but you're sending JSON.

    In your MVC controller:

    a) Add Form with File Upload:

    <form enctype="multipart/form-data" asp-controller="Product" asp-action="InsertRecord" method="post">
        <input type="text" name="productname" />
        <input type="file" name="imagepath" />
        <button type="submit">Submit</button>
    </form>
    

    b) Modify MVC Controller to Send Multipart Form Data:

    [HttpPost]
    public async Task<IActionResult> InsertRecord(tbl_product model)
    {
        using (var content = new MultipartFormDataContent())
        {
            content.Add(new StringContent(model.productname), "productname");
    
            if (model.imagepath != null && model.imagepath.Length > 0)
            {
                var streamContent = new StreamContent(model.imagepath.OpenReadStream());
                content.Add(streamContent, "imagepath", model.imagepath.FileName);
            }
    
            HttpResponseMessage response = await _Client.PostAsync(_Client.BaseAddress + "/Product/Inserprodcut", content);
            
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
        }
    
        return View(model);
    }
    
    1. Updating record with a new image

    Similar to insert, your update should also send multipart/form-data.

    MVC Update Controller:

    [HttpPost]
    public async Task<IActionResult> Updatedata(tbl_product model)
    {
        using (var content = new MultipartFormDataContent())
        {
            content.Add(new StringContent(model.productID.ToString()), "productID");
            content.Add(new StringContent(model.productname), "productname");
    
            if (model.imagepath != null)
            {
                var streamContent = new StreamContent(model.imagepath.OpenReadStream());
                content.Add(streamContent, "imagepath", model.imagepath.FileName);
            }
    
            HttpResponseMessage response = await _Client.PutAsync(_Client.BaseAddress + "/Product/Productupdate", content);
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
        }
    
        return View(model);
    }
    

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.