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.