locked
Getting variable from model to javascript RRS feed

  • Question

  • User-270429056 posted

    I'm using net core and making a Razor page. I wanted to use a variable from the model class in a javascript so that I could do a request with Ajax to get the relevant data.

    However, I am getting some strange results that I cannot explain.  
    For testing purposes, I added Id2 to check if something is wrong with the steps before this.

    public string Id { get; set; }
    public string Id2 { get; set; }
    
    public async Task<IActionResult> OnGetAsync(string id){
     Id = id;
     Id2 = "02222";
    }

    Now when I try to retrieve this data from js like this:

     <script type="text/javascript">
    var x1 = @Model.Id;
    var x2 = @Model.Id2;
    console.log("id1: " + x1);
    console.log("id2: " + x2);
    </script>

    I am not getting the variables I would expect (03043 and 02222) , I get 1170 and 1571. Where do these numbers come from? I just defined these variables now and one of them is hardcoded. If I hardcode the variable inside the js to be "02222" then it will show the correct variable, but not if I get it from the model. 
    I also tried using this:

    @page "{id:int?}"
    ...
    var id2 = @ViewContext.RouteData.Values["id"];

    But I would get 1170 instead of the expected 03043. The numbers I get are consistent so if the id is 03043 then I always get 1170 in return.

    Any ideas?
    Thanks

    Tuesday, June 23, 2020 6:55 AM

Answers

  • User991566988 posted

    Try this:

    var v = JSON.parse('@Html.Raw(Json.Serialize(Model.id))');

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 23, 2020 7:20 AM

All replies

  • User991566988 posted

    Try this:

    var v = JSON.parse('@Html.Raw(Json.Serialize(Model.id))');

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 23, 2020 7:20 AM
  • User2078676645 posted

    Hi,

    Because numbers starting with '0' are transcoded by js by default, just add single quotes to show the original number.

    var x2 = '@Model.Id2'

    Regards,

    Evern

    Tuesday, June 23, 2020 7:55 AM
  • User-270429056 posted

    Thank you, that worked!

    What is the reason why it would need to be like that? I don't understand the logic. 

    Tuesday, June 23, 2020 7:56 AM