我有一Product堂課。我有一個實體。我想在我的 Razor 頁面和我的瀏覽器 JavaScript 中訪問它。
我提出了這個想法,我可以將其渲染Product到頁面中并使用JSON.parse.
產品.cshtml:
@{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
};
}
<script>
var productJson = '@Html.Raw(JsonSerializer.Serialize(product, options))`;
var product = JSON.parse(productJson); // here I encounter error
</script>
但是我的產品有一個名為的欄位Description,在它里面我有新的生產線。因此,該JSON.parse方法抱怨:
VM27754:1 Uncaught SyntaxError: Unexpected token
in JSON at position 246
at JSON.parse ()
at :1:6
我能做什么?如何在序列化的 JSON 中轉義換行符?有沒有更好的辦法?
uj5u.com熱心網友回復:
我認為您的代碼不匹配。您應該在控制器中處理模型,然后通過 ViewModel 將物件發送到視圖。視圖所做的一切只是顯示資料。這不是程序資料。或者,如果您想使用 javascript 從服務器獲取一些資料。我認為這種情況下的 API 更好。這是我的主意。希望對你有所幫助。
謝謝
uj5u.com熱心網友回復:
你有一個錯誤,從你的代碼中洗掉“''”并發送一個 Product 實體作為模型,并在 stringfying 后使用 parse
@using System.Text.Json
@model Product
@{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
};
}
<script>
var model = @Html.Raw(JsonSerializer.Serialize(@Model, @options));
var product =JSON.parse(JSON.stringify(model));
var productName=product.name; //or product["name"]
</script>
或者代替 Text.Json,您也可以使用標準的 javascript 序列化程式
var model = @Html.Raw(Json.Serialize(@Model));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/387527.html
標籤:javascript C# json 剃刀
