2017-07-27 35 views
0

我在我的web應用程序中遇到問題,我從數據庫中檢索數據,然後將它通過ViewBag傳遞給View並最終將數據轉換爲JavaScript對象。MVC5在視圖中解析雙引號的JSON

這與僞數據

控制器

public ActionResult Index() 
{ 
    var boxer = new 
    { 
     Name = "Juan Manuel Márquez", 
     Division = "Welterweight" 
    }; 

    ViewBag.Data = new 
    { 
     Boxer = boxer 
    }; 

    return View(); 
} 

視圖的示例

<div> 
    Hello there! 
</div> 

@section scripts { 
    <script> 
     $(document).ready(function() { 
      var myModel = JSON.parse('@Html.Raw(Json.Encode(ViewBag.Data))'); 
      console.log(myModel); 
     }); 
    </script> 
} 

結果是如預期:與模型屬性的對象。但問題是,當拳擊手的名字包括他的別名,例如:

var boxer = new 
{ 
    Name = "Juan Manuel \"Dinamita\" Márquez", 
    Division = "Welterweight" 
}; 

這會導致下一個錯誤,因爲JSON.Encode生成一個JSON字符串沒有逃脫引號

VM38:1 Uncaught SyntaxError: Unexpected token D in JSON at position 31 at JSON.parse() at HTMLDocument. (Index:53) at fire (jquery-1.10.2.js:3062) at Object.fireWith [as resolveWith] (jquery-1.10.2.js:3174) at Function.ready (jquery-1.10.2.js:447) at HTMLDocument.completed (jquery-1.10.2.js:118)

任何建議?

問候

回答

1

你不需要的Json解析嘗試這裏

@section scripts { 
     <script> 
      $(document).ready(function() { 
       var myModel [email protected](Json.Encode(ViewBag.Data)); 
       console.log(myModel); 
      }); 
     </script> } 

,並刪除@ html.Raw 單引號應該看起來像

var myModel [email protected](Json.Encode(ViewBag.Data));