4

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.

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. Commented Jan 22, 2013 at 7:43
  • It's in a separate .js file Commented Jan 22, 2013 at 7:47
  • Then I don't believe you can do what you want. Commented Jan 22, 2013 at 7:52

2 Answers 2

4

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');
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

You mean the razor output is once per request but the JavaScript is cached so hard coding is the only way?
@Grokodile Yes. Razor code is converted to Javascript code on server only and sent to the browser. So, you need to hard-code only

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.