2010-11-05 66 views
1

很多人都推薦給包裹MVC JsonReturn結果在一個文本與jQuery的形式等轉換textarea的包裝JSON數據返回到原來的

這部分是有道理的,但我怎麼得到此JSON對象中發揮很好我的客戶端jQuery代碼?

客戶jQuery插件應該是這個樣子:

// Doesn't work since data is "<textarea>{"error":true,"msg":"foo"}</textarea> 
success: function (data) { 
       // strip textarea tags and convert data to json object 
       if (data['error']) { 
        // data['msg'] 
       } 
} 

感謝, 達菲

回答

2

的.html()應該拉出來的innerHTML所以

data = $.parseJSON(data.html()); 

應該做的伎倆

+0

哇,真快......不幸的是,這並不完全做的伎倆又:數據。 html()會產生TypeError:「data.html不是函數」。這並不令我感到意外,因爲數據似乎只是一個字符串。我錯過了什麼? – duffy 2010-11-05 18:55:39

+0

我想我現在明白了。 「data = $ .parseJSON($(data).html());」似乎工作。 (我仍然對jQuery不熟悉,但我想它會從字符串中創建一個dom元素?)感謝您的幫助! – duffy 2010-11-05 19:07:12

0

我明白這個問題的答案。我回復瞭如下所示的Content-Type:text/html

<textarea>{"ContentEncoding":null,"ContentType":null,"Data":{"prop1":1},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}</textarea> 

用於讀取響應的客戶端代碼。

function (xhr) 
{          
     try{ 
      console.log(xhr.responseText); 
      var originalData = $(xhr.responseText); 
      var jsonResponse = $.parseJSON(originalData.html()); 
      var propValResult = jsonResponse.Data.prop1;      
      } 
     catch (e) 
     {       

     }; 
} 

以下是我創建包裝響應的服務器端代碼。

ASP.NET MVC自定義結果

public class JsonTextWrappedResult : JsonResult 
{ 

    public override void ExecuteResult(ControllerContext context) 
    { 
     if (context == null) 
     { 
      throw new ArgumentNullException("context"); 
     } 

     if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) 
      && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) 
     { 
      throw new InvalidOperationException("Get Not Allowed"); 
     } 

     var response = context.HttpContext.Response; 
     response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; 
     if (ContentEncoding != null) 
     { 
      response.ContentEncoding = ContentEncoding; 
     } 

     if (Data != null) 
     { 
      var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
      string results = "<textarea>" + serializer.Serialize(Data) + "</textarea>"; 
      response.Write(results); 
     } 
    } 
} 

控制器代碼示例

public JsonTextWrappedResult PracticeInfoFormUpload(HttpPostedFileBase myfile, FormCollection formCollection) 
    { 


      var data = this.Json(
          new 
          { 
           prop1 = 1 
          }); 
      var result = new JsonTextWrappedResult { Data = data, ContentType = "text/html" }; 
      return result; 

    }