问题
In Razor I can do this:
<p @Html.MyCustomDataAttributeFor(person) >@person.Name</p>
To render something like this:
<p data-custom-person-id="1234567890" >Fred</p>
Must I really then do this in (unobtrusive) JavaScript:
$('p[data-custom-person-id="1234567890"]').css('background-color','red');
When I'd prefer to do this:
$('p[@Html.MyCustomDataAttributeFor(person)]').css('background-color','red');
If only I could, otherwise should the data attribute generated by the HTML helper change, my client side code will no longer style the element.
回答1:
Could you point the script to a .cshtml-file?
<script type="text/javascript" src="/myscript.cshtml"></script>
I think I've done this for both .php and .aspx so I don't see a reason it shouldn't work. In those cases it makes the server first process the file.
Otherwise you could use a customer HttpHandler that parses whatever text you want server-side before it's sent to the client.
The easiest however, would be to set some Javascript variables from Razor, ie:
<script type="text/javascript">
var customerId = '@Html.MyCustomDataAttributeFor(person)';
</script>
And then write:
$('p[' + customerId + ']').css('background-color','red');
回答2:
data-custom-person-id="1234567890"
is rendered to the browser after server has converted @Html.MyCustomDataAttributeFor(person)
to that value. On the client side you will not be receiving these text at all. So, you cannot use those statements for client side styling.
来源:https://stackoverflow.com/questions/14453704/html-helper-in-javascript