Taian
Taian

Reputation: 319

Retrieve JSON object and file in MVC

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?

Upvotes: 0

Views: 943

Answers (4)

Alexandre Rodrigues
Alexandre Rodrigues

Reputation: 730

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.

Upvotes: 1

Simon Price
Simon Price

Reputation: 3261

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?

Upvotes: 0

Jasmin Solanki
Jasmin Solanki

Reputation: 419

You can get both your logo file and your data

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

Upvotes: 0

apomene
apomene

Reputation: 14389

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.

Upvotes: 0

Related Questions