【问题标题】:How to transfer two values from controller to view, using ajax如何使用ajax将两个值从控制器传输到视图
【发布时间】:2020-03-27 12:58:37
【问题描述】:

我无法解决以下问题:

我向我的控制器发送了一个 ajax 调用,并希望返回两个值:

$.ajax({
        type: "POST",
        url: "/myController/myFunction",
        data: {
            sourceSubFunctionId: newSubFunctionId,
            destinationFunctionGroupId: FunctionGroupId
        },
        dataType: "json",
        async: false,
        error: function (Message) {
            log.error("Fehler beim Speichern der neuen Funktion.", Message);
            alert("Fehler beim Speichern der neuen Funktion.");
        },
        success: function (Message) {
            console.log(Message);
            newSubFunctionId = Message.SubFunctionId;
            newBMK = Message.BMK;
        }
    })

动作已触发,目前还可以。 现在我想取回这两个值。 我认为 Json 是正确的格式,所以我创建了一个简单的类似 json 的字符串:

 string result = "{ 'SubFunctionId': '215', 'BMK': 'myNewBMK' }";

这是控制器动作:

public JsonResult myFunction(int sourceSubFunctionId, int destinationFunctionGroupId)
    {
        string result = '{ "SubFunctionId": "215", "BMK": "MyNewBMK" }';
        //Also tried this:
        //result = Newtonsoft.Json.JsonConvert.SerializeObject(result,Newtonsoft.Json.Formatting.Indented);
        return Json(result);
    }

无论我做什么,即使是 json 也会为 unexpexted sign 抛出错误,或者我在结果中得到 undefined。

这么简单的问题,如何将我的控制器的两个字符串返回到 javascript? 它不一定是 json-farmat,有两个值的数组就可以了。

感谢卡斯滕

【问题讨论】:

    标签: javascript json ajax asp.net-mvc


    【解决方案1】:

    我假设您击中控制器的操作正确吗? 如果是这样,这就是正在发生的事情;

    你现在正在做的是你只是返回一个字符串而不是一个 json 对象。在 ajax 中收到字符串后,您可能需要将其序列化为 json 对象,以便访问其属性。

    快速解决方法是传递一个匿名对象,而不是传递一个字符串。

    试试下面的代码;

    public JsonResult myFunction(int sourceSubFunctionId, int destinationFunctionGroupId)
    {
       return Json(new {SubFunctionId="215",BMK="MyNewBMK"});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多