I have 2 rows in my loop.
I have 2 issues:
The JavaScript appears to be executing on each iteration; however, it is only populating the first table row data with the result.
I'm having to hard code the JSON object (for now) in the script, but ideally want to use a dynamic JSON string from my model data. Though whenever I try to reference it (@item.requestExample
), the JavaScript fails and the inspect/console in the browser shows that it is referencing the string and finding invalid tokens. Instead of "
it is finding "e;
. (I assume this is an HTML representation of the string?) How can I convert that to a true JavaScript object? I've tried:
var obj = JSON.parse('@(HttpUtility.HtmlDecode(@item.requestExample))');
and
var obj = dataString.replace(/"/g, '"');
both with no luck because as soon as the @item.requestExample
is referenced in the JavaScript, it is finds the invalid tokens and throws the flag.
Here is my complete loop in the mvc view:
@foreach (var item in Model.list)
{
<tr class="table-info">
<td>@item.library</td>
<td>@item.api</td>
<td>@item.ibmiPgm</td>
<td> <pre id="uglyPretty"></pre> </td>
<script>
var pretty = document.getElementById("uglyPretty");
var obj = { "success": 1, "resultMessage": "Success", "list": [{ "custNo": "101", "firstName": "First Name: 101", "lastName": "Last Name: 101", "address1": "Address1: 101", "address2": "Address2: 101", "city": "City: 101", "state": "10", "zip": "101", "routing": "101", "accountNo": "101" }, { "custNo": "102", "firstName": "First Name: 102", "lastName": "Last Name: 102", "address1": "Address1: 102", "address2": "Address2: 102", "city": "City: 102", "state": "10", "zip": "102", "routing": "102", "accountNo": "102" }] };
document.getElementById("uglyPretty").innerHTML = JSON.stringify(obj, undefined, 2);
</script>
<td>
<button typeof="button" onclick="location.href='@Url.Action(item.api, "", new { api = item.api, jsonRequest = item.requestExample } )'">Consume API</button>
</td>
</tr>
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…