1

I want to upload image and file in my wwwroot folder using a partial view. I use an ajax form to submit data but i get null value in 'HttpContext.Request.Form.Files' section. when i remove ajax properties in form tag everything works fine.

Partial View :

@model LibraryProject.Models.ViewModels.AddBookViewModel


<form asp-controller="Book" asp-action="AddBook" id="frmaddbook" data-ajax="true" data-ajax-method="POST"
  data-ajax-update="#frmaddbook" data-ajax-mode="replace" enctype="multipart/form-data">


<div class="modal-body form-horizontal">
    <div class="row">

        <div class="form-group">
            <label asp-for="BookName" class="col-lg-2 col-sm-2 control-label"></label>
            <div class="col-lg-6">
                <input asp-for="BookName" class="form-control" />
                <span asp-validation-for="BookName" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <label asp-for="BookDescription" class="col-lg-2 col-sm-2 control-label"></label>
            <div class="col-lg-9">
                <textarea id="BookDescription" name="BookDescription" asp-for="BookDescription" class="form-control"></textarea>
                <span asp-validation-for="BookDescription" class="text-danger"></span>
            </div>

            <script type="text/javascript">
                CKEDITOR.replace('BookDescription');
            </script>

        </div>


        @* Image *@
        <div class="form-group">
            <label asp-for="BookImage" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="BookImage" type="file" name="file" />
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-10">
                <input type="submit" value="SaveInDataBase" />
            </div>
        </div>
    </div>
</div>

Controller :

 public class BookController : Controller
 {
    private readonly ApplicationDbContext _context;
    private readonly IServiceProvider _iServiceProvider;
    private readonly IHostingEnvironment _appEnvironment;

    public BookController(IHostingEnvironment appEnvironment, ApplicationDbContext context, IServiceProvider iServiceProvider)
    {
        _context = context;
        _iServiceProvider = iServiceProvider;
        _appEnvironment = appEnvironment;
    }
.
.
.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> AddBook(AddBookViewModel model)
    {
        if (ModelState.IsValid)
        {
                //here returns null
                var files = HttpContext.Request.Form.Files;
                foreach (var Image in files)
                {
                    if (Image != null && Image.Length > 0)
                    {
                        var file = Image;
                        var uploads = Path.Combine(_appEnvironment.WebRootPath, "uploads\\img\\");
                        if (file.Length > 0)
                        {
                            var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
                            using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);
                                model.BookImage = fileName;
                            }
                        }
                    }
                }


                //insert
                using (var db = _iServiceProvider.GetRequiredService<ApplicationDbContext>())
                {
                    Book bookmodel = AutoMapper.Mapper.Map<AddBookViewModel, Book>(model);
                    db.books.Add(bookmodel);
                    db.SaveChanges();
                }
                return PartialView("_succefullyresponse", redirectUrl);
            }

        return PartialView("_AddEditbook", model);
    }
}

Model :

public class AddBookViewModel
{
    [Key]
    public int BookId { get; set; }

    [Display(Name = "Name  :")]
    [Required]
    public string BookName { get; set; }

    [Display(Name = "Description :")]
    [Required]
    public string BookDescription { get; set; }

    [Display(Name = " Image :")]
    public string BookImage { get; set; }
}

I wrote all of my code above. Now the question is how can i upload image or file in wwwroot//img folder when data post through ajax form?

topcool
  • 2,498
  • 7
  • 28
  • 52
  • Use `FormData` to upload files with ajax (refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for an example (and delete the obsolete `data-ajax-* attributes in your `
    `
    –  Nov 09 '17 at 21:00

0 Answers0