Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • saif 68 posts 88 karma points
    Feb 22, 2012 @ 10:52
    saif
    0

    access razor variable in jQuery

    Hi All,

    I am trying to access value of a variable 'name' using jQuery which is defined in razor code.

    @{
      
        var name = school name from database ;

    }

    <!DOCTYPE html>
    <html>
    <head id="Head1" runat="server">

    <script type="text/javascript">

     $(function () {

    alert("school name is: "+name)

     });

     </script>

    Please give me an idea how to get that name in jQuery script.

    kind regards.

     

  • Euan Rae 105 posts 135 karma points
    Feb 22, 2012 @ 11:26
    Euan Rae
    1

    You can't access razor variables in query as razor is rendered server side, and jQuery is client side.  You could however put the output of the razor variable in some type of html element and get that in jQuery

    e.g.

    @{
       
        var name = school name from database ;

       <input id="schoolName" value="@name"/>

    }

    <script>

    $(function () {

    alert("school name is: " + $('# schoolName');

     });

     </script>

     

  • saif 68 posts 88 karma points
    Feb 22, 2012 @ 11:59
    saif
    0

    Euan, thanks for your speedy response – that’s exactly what I was looking for.

    The only one thing I suggest is to include .val() (you may have left it out intentionally)

    I would replace

    alert("school name is: " + $('# schoolName');

    with

    alert("school name is: " + $('# schoolName').val());

    thanks

Please Sign in or register to post replies

Write your reply to:

Draft