【问题标题】:ASP.NET MVC Ajax JSON jQuery won't send parameters to `ActionResult`ASP.NET MVC Ajax JSON jQuery 不会将参数发送到“ActionResult”
【发布时间】:2019-04-05 11:01:25
【问题描述】:

我使用 jQuery 和 JSON 构建了一半工作的 ajax 代码,但我无法从 POST 请求中获取数据参数,尽管我尝试以几种不同的方式发送它(首先作为 data: {} 对象中的对象,然后只是字符串),但没有任何效果。代码如下:

C#,ManageController.cs:

public ActionResult SubmitForm(string typeAction)
        {
            string message = (int.Parse(typeAction) * 20).ToString();//Exception: can't convert null string to int
            return Json(new  {Message = message, JsonRequestBehavior.AllowGet}); 
        }

JavaScript(当然是 +jQuery)、AppScripts.js:

function AjaxPost(typeofAction, ActionUrl) {    
    $.ajax({
        type: "POST",
        url: ActionUrl,
        data: { typeAction: JSON.stringify(typeofAction) },
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            return true;
        },
        error: function (xhr, textStatus, errorThrown) {
            console.error(textStatus + "\n" + errorThrown);
        }
    });
    return false;
}

从按钮调用:

<button onclick="AjaxPost($('#SimpleActionId').value, '/manage/SubmitForm')">Go!</button>

对于结果,操作被调用,我可以看到它由调试器执行,直到抛出异常,因为无法将空字符串转换为 int。该参数甚至没有进入ActionResult SubmitForm,但是它被调用了,并且所有的值都是从数据中发送的。 谢谢。

【问题讨论】:

  • 因为model binding 不会发生并且字符串参数将始终为空
  • 好的。那么如何正确获取值呢?

标签: jquery json ajax asp.net-mvc


【解决方案1】:

1) 将您的 AJAX 调用修改为如下所示:

function AjaxPost(typeofAction, ActionUrl) {    
    $.ajax({
        type: "POST",
        url: ActionUrl,
        data: JSON.stringify({ typeAction: typeofAction }),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data);
            return true;
        },
        error: function (xhr, textStatus, errorThrown) {
            console.error(textStatus + "\n" + errorThrown);
        }
    });
    return false;
}

2) 制作 C# 模型:

public class ActionType
{
    public string typeAction { get; set; }
}

3) 将您的操作方法更改为如下所示:

public ActionResult Edit(ActionType RequestModel)
{
    string message = (int.Parse(RequestModel.typeAction) * 20).ToString();
    return Json(new  {Message = message }, JsonRequestBehavior.AllowGet); 
}

现在将发生适当的model binding,您将把您的typeAction 放入RequestModel.typeAction 属性中。

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多