0

I am using ajax to pass a viewmodel, that includesa an HttpPostedFileBase to my API controller. The controller gets the viewmodel with all the values, but for the Image property from the model comes null. How can I fix this problem?

viewModel:

 public class MyViewModel
{
    public Guid Id{ get; set; }
    [MaxLength(125)]
    public string SomeValue{ get; set; }
    public readonly short TituloLength = 125;        
    [DataType(DataType.Upload)]
    public HttpPostedFileBase Image { get; set; }
}

API snippet

  public IHttpActionResult UpdateThis([FromBody] MyViewModel viewmodel)
    { //here goes some more code
            return Ok(result);
    }

Html Form

<form id="myForm" method="post" action="#" enctype="multipart/form-data">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "Please fix the following errors.")
<div class="container">
    <div class="form-group">
        @Html.LabelFor(c=>c.SomeValue)
        @Html.TextBoxFor(c => c.SomeValue, new { @class="form-control"})           
        @Html.ValidationMessageFor(m => m.SomeValue)
    </div>    
    <div class="thumbnail" id="imagencurso"></div>
    <div class="form-group">
        @Html.LabelFor(m => m.Image)
        @Html.TextBoxFor(m => m.Image, new {type = "file",name="Image"})
        @Html.ValidationMessageFor(m => m.Image)
    </div>
    <button id="letssubmit" type="submit" class="btn btn-primary">Lets Go!</button>
</div>

AJAX for my view, I create an object that is passed via ajax to my controller.

$('#myForm').submit(function(e) {
            e.preventDefault(); // prevent the default submit
            if (!$(this).valid()) {
                return; // exit the function and display the errors
            }

            jQuery.support.cors = true;
            var files = $("#Image").get(0).files;//get file from input

            var MyViewmodel = new Object();
            MyViewmodel .SomeValue= "Hi everyone";
            MyViewmodel .Id = [guid comes here];
            MyViewmodel .Imagen = files[0];

            $.ajax({
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                url: '/api/myApi/UpdateThis',
                type: 'PUT',
                dataType: 'json',
                data: JSON.stringify(MyViewmodel),
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log('success');
                    return false;
                },
                error: function () {
                    alert('error');
                    return false;
                }
            });
        });

When I press the button to send a request to my API, the action "UpdateThis" is working, but the viewmodel.Image=null.

How can I fix it and get my image? thank you.

  • 1
    You need to use `FormData` to submit files using 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) –  Sep 18 '17 at 04:11

1 Answers1

0

After this :

jQuery.support.cors = true;

Add these lines of code

var fileupload = $("#fileuploader").get(0);

var files = fileupload.files;
var filedata = new FormData();

for (var i = 0; i < files.length; i++) {
    filedata.append(files[i].name, files[i]);
}

And add this filedata to your Myviewmodel object.

And to get the files count on C#

Use: Context.Request.Files.Count