Faisal
Faisal

Reputation: 604

Upload file with .net core MVC using ajax and pass as model

i'm trying to upload image using .net core with mvc ajax

here is my code

<form asp-action="AddImages" asp-controller="UserAdmin"
                      data-ajax-begin="onBeginSubmit" data-ajax-complete="onComplete"
                      data-ajax-failure="onFailed" data-ajax-success="onSuccessSubmit"
                      data-ajax="true" data-ajax-method="POST" enctype="multipart/form-data">
                                <input id="file-input-1" name="Image" type="file" class="uploadimg" data-id="1" accept=".jpg, .jpeg, .png" />

                    <div class="col-xs-12">
                        <button type="submit">Save</button>
                    </div>
                </form>

Here is my Model

public class ImageModel
    {
        [Required(ErrorMessage = "Please Select Image of Product")]
        public List<IFormFile> Image { get; set; }
    }

And my method

  [HttpPost]
        public bool AddImages(ImageModel Image)
        {
            if (!ModelState.IsValid)
            {
                return false;
            }
            return true;
        }

but Image is null and model always return false

Upvotes: 2

Views: 3666

Answers (1)

Ashdog
Ashdog

Reputation: 31

I've just come up against this problem myself, and it seems the only way around it is to use "traditional" ajax to post the form back to the controller. My method was as follows:-

Replace the Submit button with a normal button that calls the Ajax:

<input type="button" class="btn btn-default" value="Save" onclick="javascript:submitForm()" />

Then use Ajax to gather the form data and post it back to the controller action:

 function submitForm() {
    var formdata = new FormData($('#yourFormId').get(0));
    $.ajax({
        url: '@Url.Action("YourActionName", "YourControllerName")',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false,
        success: function (data) {
            //rendering success
        },
        error: function (xhr, ajaxOptions, thrownError) {
            //rendering errors
        }
    });
}

Hope this helps somebody out. Shame the new "data-ajax" form tags don't seem to be able to handle posting files back.

Upvotes: 3

Related Questions