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.
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.
Share Improve this question edited Jan 22, 2013 at 7:47 Grokodile asked Jan 22, 2013 at 7:38 GrokodileGrokodile 3,9235 gold badges36 silver badges61 bronze badges 3- 1 Is this javascript in a view file? What server side language are you using? If the JS is in a view file (where I'd assume your Razor code is) then you should be able to do what you want. – matthewpavkov Commented Jan 22, 2013 at 7:43
- It's in a separate .js file – Grokodile Commented Jan 22, 2013 at 7:47
- Then I don't believe you can do what you want. – matthewpavkov Commented Jan 22, 2013 at 7:52
2 Answers
Reset to default 4Could 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');
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744276973a4566378.html
评论列表(0条)