P-Finny
P-Finny

Reputation: 261

jQuery + MVC pass string to controller

I'm trying to do something I would think is fairly simple, but I must be missing the syntax.

function removeFile(filename) {
    var json = { "fileName": filename };
    $.ajax({
        type: 'post',
        url: "home/RemoveFile",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(json),
        success: function(result) {
            alert("good:" + result);
        },
        failure: function (response) {
            alert("bad:" + response.d);
        }
    });    
}

And to receive the filename in the controller:

[HttpPost]
public JsonResult RemoveFile(string fileName)
{
    if (fileName == null) return Json(" {'result' : 'failure'}");
    FileUpload fileUpload = new FileUpload(_hostingEnvironment, _settings);
    Boolean removeFile = fileUpload.RemoveFile(fileName);
    return Json(" {'result' : 'ok'}");
}

the fileName is always null, yet Fiddler shows the Json being passed as:

- JSON
     -fileName=2851cd1d-f364-4f00-8824-0792cf6ca598\Capture-after.JPG

What am I doing wrong?

Upvotes: 1

Views: 958

Answers (2)

Shyju
Shyju

Reputation: 218722

When you specify the contentType as application/json, the $.ajax method will send data in the request body.

Since you are sending a lean-flat data object, send the js object in the data property. The $.ajax method will convert this js object to Form Data when the call is made.

var json = { fileName: 'myfile.png' };
$.ajax({
    type: 'post',
    url: "home/RemoveFile",
    data: json,
    success: function(result) {
        alert("good:" + result);
    },
    failure: function (response) {
        alert("bad:" + response.d);
    }
});

Use a JSON string of your object ( the result of JSON.stringify(json)) as data when you want to send a complex js object ( not just a lean-flat view model). Make sure you are specifying the contentType header to application/json so that the server know what type of data it is receiving and how to do model binding.

Also do not build a json string in server. Let the json serializer does that for you. Pass an anonymous object to your Json method.

return Json(new {result = "ok"});

Your existing code where you are sending the JSON string as the data and contentType as application/json, will work if you have a view model with fileName property.

public class MyViewModel
{
    public string FileName { set; get; }
}

and in the action method. Use this view model as the parameter along with [FromBody] decorator.

[HttpPost]
public JsonResult RemoveFile3([FromBody]MyViewModel f)
{       
    return Json(new {result = f.FileName});
}

Upvotes: 1

Korio
Korio

Reputation: 84

Ty to remove JSON.stringy from the data. Since you are putting "dataType:json" it's expecting a json.

Upvotes: 2

Related Questions