0

I am working with Ajax, mvc and c#, uploading my model to my api action, using this information I found here: stackoverflow: How to append whole set of model to formdata and obtain it in MVC.

This is my problem When following step by step the above link, my model in the api side comes null:

//this is the conten of the viewmodel object in the api action
guid:{00000000-0000-0000-0000-000000000000}
descripcion:null
Imagen:null
Title:null

This is my viewmodel

  public class myViewModel
{
    public Guid CursoId { get; set; }
    [MaxLength(125)]
    public string Titulo { get; set; }
    public string Descripcion { get; set; }
    [Required(ErrorMessage = "select image file for course")]
    [DataType(DataType.Upload)]
    public HttpPostedFileBase Imagen { get; set; } //note this is the image
}

My web api, it is a simple action to test

 // POST: api/Test
    [Route("test")]
    public void Post([FromBody]myViewModel model)
    {//do something
    }

this is my view:

 @model ajaxtest.ViewModel.myViewModel
<form id="Editcurso" 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.Titulo)
        @Html.TextBoxFor(c => c.Titulo, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Titulo)
    </div>
    <div class="form-group">
        @Html.LabelFor(c => c.Descripcion)
        @Html.TextAreaFor(c => c.Descripcion, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Descripcion)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Imagen)
        @Html.TextBoxFor(m => m.Imagen, new { type = "file" })
        @Html.ValidationMessageFor(m => m.Imagen)
    </div>
    <button id="submiter" type="submit" class="btn btn-primary">Listo!</button>
</div>

Here is my javascript:

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


            jQuery.support.cors = true;
          // Create a formdata to pass the model, since the view was generated from viewmodel, it should contain the model.
            var model = new FormData($('#Editcurso').get(0));

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

            e.preventDefault(); // avoid to execute the actual submit of the form.
        });

    });

What do you think is wrong and how can I fix it? thanks.

ev vk
  • 345
  • 1
  • 4
  • 18
  • Start by removing `headers: { ... }` and its `data: model,` (not stringified) –  Sep 19 '17 at 01:18
  • if I remove the headers, I get this error: POST http://localhost:52922/api/test/test 415 (Unsupported Media Type) – ev vk Sep 19 '17 at 01:23
  • You cannot use `Content-Type': 'application/json` is your uploading a file. Refer [this answer](https://stackoverflow.com/questions/10320232/how-to-accept-a-file-post) for an example (I'll see if I can find a better one shortly) –  Sep 19 '17 at 01:28
  • @StephenMuecke thanks, I will check it. As another comment, I am still getting the unsupported media type – ev vk Sep 19 '17 at 01:33

0 Answers0