如何序列化模型,并在ajax请求中将其传递给MVC控制器 [英] How to serialize model, pass it to MVC controller in ajax request

查看:101
本文介绍了如何序列化模型,并在ajax请求中将其传递给MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我的页面模型传递给我的控制器进行处理。
处理完信息后,我想更新id为savedText的div,以显示账单信息已成功保存。

I'm trying to pass my page's model to my controller for processing. After processing the information, I want to update the div of id "savedText" to display "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;
}

我在控制器中有这个:

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

我做错了什么?

在chrome中的检查元素时,在网络标签中,表示没有找到我的控制器方法。

When "inspecting element" in chrome, in the network tab, it's saying that my controller method isn't found.

另外,这对我很重要将整个模型从视图中获取到控制器的函数中(本例中为TestingFunction),以便我可以获取表单信息并保存它。我试着使用.serialize()函数,但这会导致obj =(空字符串)。

Also, it's important for me to get the entire model from the view into the controller's function (TestingFunction in this case) so that I can get the form information and save it. I'm trying the .serialize() function but that results in obj = (empty string).

推荐答案

/ p>

Three things:


  1. $('testForm')应该可以是 $ ('.testForm') $('#testForm')。因为它正在尝试选择< testForm>< / testForm>

  2. 如果您只是发送
  3. 尝试做一个发布请求:

  1. $('testForm') should probably be $('.testForm') or $('#testForm'). As it is you're trying to select a <testForm></testForm>.
  2. If you're just sending the form, it doesn't need to be json.
  3. Try doing a post request:







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

这篇关于如何序列化模型,并在ajax请求中将其传递给MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆