Home > Back-end >  Razor Page - String with whitespace from C# code is shortened when stored in html data attribute
Razor Page - String with whitespace from C# code is shortened when stored in html data attribute

Time:11-06

I am working on Razor Page (.NET Core 6) and trying to store data in html data attribute. The problem is that: if the data is the string from C# code and it has whitespace, the string will be split by whitespace and stored only the first item.

For example, if I store a static string directly in data attribute ("data-comment" in this case), it will work perfectly fine (the log show "abc def" correctly):

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div>
    @{
        <input id="input_data" type="text" data-comment="abc def" />
        <button onclick="LogComment();">Log</button>
    }
</div>
@section Scripts {
    <script type="text/javascript">
        function LogComment() {
            const comment = $("#input_data").data("comment");

            console.log(`comment: ${comment}`);    //> comment: abc def
        }
    </script>
}

However, when I get the string data from C# code the string will be shorthened to only "abc":

...
<div>
    @{
        string comment = "abc def";

        <input id="input_data" type="text" data-comment=@comment />
        <button onclick="LogComment();">Log</button>
    }
</div>
@section Scripts {
    <script type="text/javascript">
        function LogComment() {
            const comment = $("#input_data").data("comment");

            console.log(`comment: ${comment}`);    //> comment: abc
            // Also, if the string is null, the log will return "comment: /" (with slash)
        }
    </script>
}

CodePudding user response:

You have to add quotes around the attribute value:

<input id="input_data" type="text" data-comment="@comment" />

When you omit the quotes the generated html result is the following:

<input id="input_data" type="text" data-comment="abc" def>

So this is why $("#input_data").data("comment"); returns "abc". It is always helpful to use your browser's developer tools to inspect the generated html output.

  • Related