2

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>
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This, but it could be worth explaining that otherwise it would result in <input data-comment=abc def /> which in html would add a separate property called def

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.