skip to Main Content

I was working on Razor page with MVC. I want to get model values in Javascript to update the table dynamically.
I am using below code to pass index dynamically.

var page1 = JSON.parse("@Html.Raw(JsonSerializer.Serialize(Model.conditionList["+ i +"]))");

But it throws error as

RuntimeBinderException: The best overloaded method match for ‘System.Collections.Generic.Dictionary<int,object>.this[int]’ has some invalid arguments.

Instead of double quotes I have tried with single quotes as below

var page1 = JSON.parse('@Html.Raw(JsonSerializer.Serialize(Model.conditionList['+ i +']))');

But in this case I’m getting synatx error

Too many characters in character literal

If I use hardcoded index it is working perfectly:

var page1 = JSON.parse('@Html.Raw(JsonSerializer.Serialize(Model.conditionList[0]))');

Any help would be highly appreciated.

2

Answers


  1. Double quotes stands for string values and single quotes stands for character values in Razor pages.
    You can try to use backtick template literals to pass index dynamically

    var page1 = JSON.parse(`@Html.Raw(JsonSerializer.Serialize(Model.conditionList[${i}]))`);
    
    Login or Signup to reply.
  2. The original line of code in your post:

    var page1 = JSON.parse("@Html.Raw(JsonSerializer.Serialize(Model.conditionList["+ i +"]))");

    looks like an attempt to write "@Html.Raw(JsonSerializer.Serialize(Model.conditionList["+ i +"]))" as a string into the HTML content stream that will be processed on the client. You’re concatenating three strings together: "@Html.Raw(JsonSerializer.Serialize(Model.conditionList[" linked with the value of the variable i linked with "]))".

    The following will be processed correctly in a Razor page.

    let page1 = JSON.parse('@Html.Raw(JsonSerializer.Serialize(Model.conditionList[i]))');
    

    assuming the variable ‘i’ is defined within a Razor syntax (e.g. int i = 1; }).

    Breaking down the above line of code:

    JsonSerializer.Serialize(Model.conditionList[i]) is C# code processed on the server when the Razor page is parsed.

    The Razor engine then uses @Html.Raw() to render the string result from JsonSerializer.Serialize(Model.conditionList[i]) into the HTML content stream. The content stream is added to the HTTP response that’s sent to the client.

    After the client browser parses and renders the HTML in the response, the JavaScript engine executes the JSON.parse() method on the serialized string embedded within the parenthesis of the JSON.parse() method. For example:

    JSON.parse('["abc","def"]');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search