c# - 如何序列化模型,在 ajax 请求中将其传递给 MVC Controller

标签 c# jquery html ajax asp.net-mvc

我正在尝试将我的页面模型传递给我的 Controller 进行处理。 处理完信息后,我想更新id为“savedText”的div来显示“Billing Information saved successfully”。

我有这个想法

function testingFunction() {
    var obj = $('testForm').serialize();

    $.ajax({
        url: '@Url.Action("TestingFunction", "BuildGiftCard")',
        dataType: 'json',
        success: function (result) {
            $("#savedText").html(result);
        },
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(obj)
    });

    return false;
}

我的 Controller 中有这个:

[HttpPost]
public JsonResult TestingFunction(PurchaseModel model)
{
    return Json("Billing information saved successfully.");
}

我做错了什么?

当在 chrome 中“检查元素”时,在网络选项卡中,它说找不到我的 Controller 方法。

此外,将整个模型从 View 获取到 Controller 的函数(在本例中为 TestingFunction)对我来说很重要,这样我就可以获取表单信息并保存它。我正在尝试 .serialize() 函数,但结果是 obj =(空字符串)。

最佳答案

三件事:

  1. $('testForm')应该是 $('.testForm')$('#testForm') .事实上,您正在尝试选择 <testForm></testForm> .
  2. 如果您只是发送表单,则不需要是 json。
  3. 尝试做 post要求:

$.ajax({
    url: '@Url.Action("TestingFunction", "BuildGiftCard")',
    dataType: 'json',
    success: function (result) {
        $("#savedText").html(result);
    },
    data: $('#testForm').serialize(),
    type: 'POST'
});

关于c# - 如何序列化模型,在 ajax 请求中将其传递给 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24944495/

相关文章:

c# - 无法解析远程名称 : 'xxx.table.core.windows.net'

javascript - onsubmit 刷新 html 表单

html - 网站容器不会与中心对齐(移动和网络)

jquery - 如何使用查询字符串值设置 Wufoo 输入?

javascript - 如何在面板前后添加面板

javascript - 如何在 div 中显示文本编辑器并在单击按钮后显示添加的内容?

html - 打开关闭sidenav相同的按钮

c# - Delphi 函数转 C#

c# - 预购通用列表 C#

c# - 将 Base64 字符串转换为位图或图像 Xamarin 或 Android