0

I have the following client-side code to send a JSON object and a file to MVC using JQuery ajax:

var formData = new FormData();
formData.append('logo', logoImg);
var objArr = [];

objArr.push({"id": id, "name": userName});

//JSON obj
formData.append('ocorrencia', JSON.stringify( objArr ));


$.ajax({
    url: "/Ocorrencia/Edit",
    type:"POST",
    processData:false,
    contentType: false,
    data: formData,
        complete: function(data){
                    alert("success");
            }
  });

On the server-side, I'm using ASP.NET MVC.

[HttpPost]
public JsonResult Edit()
{
    // How to retrieve the data and the file here?

I have a model to the "ocorrencia". What do I have to do to retrive the model and the file on the server side?

3
  • You could try adding GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new RequestHeaderMapping("Accept", "text/html", StringComparison.InvariantCultureIgnoreCase, true, "application/json")); to the Register method of WebApiConfig.cs Commented May 17, 2019 at 13:25
  • @schlonzo , what does it do? Commented May 17, 2019 at 13:30
  • @Taian is my answer the correct one? :) Commented May 17, 2019 at 13:51

4 Answers 4

1

Try using FromBodyAttribute

using System.Web.Http; 
public JsonResult Edit([FromBody]List<Ocorrencia> ocorrencia,HttpPostedFileBase logo)
{
}

Edited

using System.Web.Http can be added by Microsoft.AspNet.WebApi.Core package on NuGet.

Sign up to request clarification or add additional context in comments.

6 Comments

I'm having the error "The type or namespace 'FromBody' could not be found". =(
@Taian you have to use using Microsoft.AspNetCore.Mvc;
I'm not using AspNetCore, I'm just using AspNet.
so use using System.Web.Http; :)
There's no System.Web.Http there too =(
|
0

You just need to correctly define the Action signature on your controller and use Newton Json. Like:

[HttpPost]
public JsonResult Edit(List<Ocorrencia> ocorrencia)
{
  var model = JsonConvert.DeserializeObject<List<Ocorrencia>>(ocorrencia);
   ...

Above code assumes that you have a class named Ocorrencia.

Comments

0

You can get both your logo file and your data

public JsonResult Edit(List<Ocorrencia> ocorrencia,HttpPostedFileBase logoImg)
{
}

Comments

0

Im going to say that your ajax is wrong, your midding content and dataType

This is an example of what I am using right now and works perfectly

 $.ajax({
        type: "POST",
        headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
        url: url,
        data: JSON.stringify(model),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            ... success code here
        },
            error: function (x, y, z) {
            }
        });

I define my model like

var model = {
             myObject: "somevalue"
             myOtherObject: 2
             }

Url is obvious

and then

[HttpPost]
[Route("sign")]
public async Task<IActionResult> Sign([FromBody]ReportLessonSign model)
{
 // your code in here
}

At this point the json object is passed into my model and handled accordingly.

With regards to your file, how are you trying to pass this up?

1 Comment

When I define the dataType, I cannot send the file. The dataType must be set to false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.