【问题标题】:Return two values back to Ajax from controller将两个值从控制器返回给 Ajax
【发布时间】:2017-05-06 09:47:51
【问题描述】:

是否可以从控制器返回 false 和其他数据类型(如 int、bool 等)返回 Ajax?

 $.post('/Home/SomeAction', { "id": Id }, function (data) {
                if (data) {  
                     ...
                   }else if(data.anotherBool == true){
                   //....
                   }

我需要三个不同用途的树值,true、false 和另一个布尔值。

 public JsonResult SomeAction(int id) {

        ........

       return Json(false, anotherBoolean); //<-- what I want
  }

【问题讨论】:

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


    【解决方案1】:

    是的,您可以使用JSON 来做到这一点。从你的控制器尝试这样的事情:

    public JsonResult yourFunctionName()
    {
          // your code here
          return Json(new {booleanValue = anotherBoolean, intValue = anotherIntValue}, JsonRequestBehavior.AllowGet);
    }
    

    此外,您可以像这样在 Ajax 调用中获取值:

    $.post('/Home/SomeAction', { "id": Id }, function (data) {
                if (data.intValue == 1) {  
                   //....
                }
                else if(data.booleanValue == true){
                   //....
                }
    

    【讨论】:

    • 需要为$.post设置dataType
    • @Senjuti Mahapatra ...请帮助我,我想传递消息作为回报,这怎么可能?在mvc中
    • @Brij - 你可以这样做return Json(new {booleanValue = anotherBoolean, intValue = anotherIntValue, message = "some string"}, JsonRequestBehavior.AllowGet);
    【解决方案2】:
    public JsonResult FunctionName()
    {
          // do your coding
    var result=Json(new {param1 = val1 , param2 = val2});
          return Json(result, JsonRequestBehavior.AllowGet);
    }
    

    在 Json 中获取值:

    var val1 = response.Data.param1;
    
    var val2 = response.Data.param2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 2020-08-13
      相关资源
      最近更新 更多