【问题标题】:C# - Get Ajax dataC# - 获取 Ajax 数据
【发布时间】:2014-12-27 21:08:19
【问题描述】:

我想通过 Ajax 将数据发送到 C# 文件,但是当我检查接收到的数据时,它给了我 null。我的代码有问题吗?

Javascript 文件

 $(".save").click(function () {
    var ss = "Helloo!";
    $.ajax({
        type: "POST",
        url: "/Notes/save.cshtml",
        global: true,
        data: {fofo: ss},
        processData: false,
        contentType: false,
        cache: false,
        success: function(data){
  console.log(data);
 },
        error: function (req, status, error) {
            alert("There was a problem with the server. Try refreshing the page.");
            return false;
        }
    });
});

接收数据的C#文件(save.cshtml)

@{
  var s = Request.Form["fofo"];
 var result = "";
    var userData = s;

    var dataFile = Server.MapPath("~/Notes/lolo.txt");
    File.WriteAllText(@dataFile, s);
    result = "Information saved.";
}
 @if(result != ""){
    <p>Result: @result, @s</p>

}

【问题讨论】:

  • 这是表格吗?如果.save 是 type=submit 则需要阻止默认提交

标签: javascript c# jquery ajax


【解决方案1】:

您没有将response 发送回您的AJAX 函数。不仅你所做的不是标准的MVC。您应该点击Controller,它将数据保存在服务器端的文件中,然后使用JsonResult 将结果发回。

例如:

public JsonResult SaveNotes()
{
    // Code to save file here

    // Return the response 
    return Json({NotesSaved = true});
}

然后在您的JavaScript AJAX 成功对象中,您会将NotesSaved 对象设置为true。

注意:您还应该将AJAX 命令中的URL 参数更改为:

 url: '@Url.Action("SaveNotes")'

【讨论】:

  • 如果使用外部 js 文件,最后一部分将不起作用
  • @charlietfl - 这是真的.. 他将不得不使用静态字符串或通过全局对象传递它。我会更新我的答案以包括这个。我认为重点是它应该通过Controller
猜你喜欢
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 2018-04-09
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多