Search code examples
javascriptrazor-pages

JavaScript sorting function unless I put Model.column and Model.order in quotation marks


I recently started learning c# and I'm doing a course on razor pages. I have a table of books and I want to be able to sort it by clicking on the column headings. This is my JavaScript function:

function sortTable(column)
{
    let order = "desc";
    let currentColumn = @Model.column;
    let currentOrder = @Model.order;

    if (column == currentColumn && currentOrder == "desc") 
    {
        order="asc";
    }

    window.location.href = "[email protected]&column=" + column + "&order=" + order;
}

When I click on a heading, nothing happens. If I do the following instead, it works:

    let currentColumn = "@Model.column";
    let currentOrder = "@Model.order";

The variables are declared as strings in the model, so I really don't know why it isn't working.


Solution

  • The variables are declared as strings in the model

    That is just their internal type. But you are creating code here, so you need to abide by the rules of the syntax of the language you are creating code in.

    Text literals in JavaScript need some kind of quotes around them. Those quotes are not included in the values of your variables (if the were, then you would also end up with window.location.href = "?search="someSearchValue"&column=..." there, which would make rather little sense), so you need to add them the moment you are trying to create code out of this data.