HTML Helper in JavaScript?

余生颓废 提交于 2019-12-22 09:59:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!