jQuery + MVC将字符串传递给控制器

时间:2017-11-10 17:59:21

标签: jquery asp.net-mvc

我正在尝试做一些我认为相当简单的事情,但我必须忽略语法。

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);
        }
    });    
}

并在控制器中接收文件名:

[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'}");
}

fileName始终为null,但Fiddler将Json传递为:

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

我做错了什么?

2 个答案:

答案 0 :(得分:2)

Ty从数据中删除JSON.stringy。因为你要放“dataType:json”所以它期待一个json。

答案 1 :(得分:1)

当您将contentType指定为application / json时,$.ajax方法将在请求正文中发送数据。

由于您要发送精简数据对象,请在data属性中发送js对象。调用时,$ .ajax方法会将此js对象转换为Form Data。

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);
    }
});

如果要发送复杂的js对象(不仅仅是精简平面视图模型),请将对象的JSON字符串(JSON.stringify(json)的结果)用作data。确保将contentType标头指定为application/json,以便服务器知道它接收的数据类型以及如何进行模型绑定。

也不要在服务器中构建json字符串。让json序列化器为您做到这一点。将匿名对象传递给Json方法。

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

如果您的视图模型具有fileName属性,那么您将JSON字符串作为数据发送到的现有代码将contentType作为application/json发送。

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

并在动作方法中。将此视图模型与[FromBody]装饰器一起用作参数。

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