SoloThink
SoloThink

Reputation: 41

C# function calling to cshtml

I am not able to call a function in my CSHTML page.

in my cshtml page script :

 <script type="text/javascript" >
        //var sLoggedInUser = <%# GetSession_LoggedInIdUser() %>;
        $(document).ready(function () {
            alert("dom");

            var sLoggedInUser = PageMethods.GetSession_LoggedInUserName();          

            alert(sLoggedInUser);
        });


        function btnClick() {
            alert("btn click");
        }

    </script>

dom is alerted, button click function work well, but get no value of sLoggedInUser. In my cs page:

 protected string GetSession_LoggedInUserName()
        {
            SessionConfiguration Obj_Configuration = (SessionConfiguration)Session["Configuration"];
            return Obj_Configuration.LoggedInUserName;
        }

I also try with : var sLoggedInUser = <%= PageMethods.GetSession_LoggedInUserName() %> // var sLoggedInUser = GetSession_LoggedInUserName()

Upvotes: 0

Views: 903

Answers (3)

Jitendra Tiwari
Jitendra Tiwari

Reputation: 1691

Declare your function public static instead of protected

public static string GetSession_LoggedInUserName()
{
        SessionConfiguration Obj_Configuration = (SessionConfiguration)Session["Configuration"];
        return Obj_Configuration.LoggedInUserName;
}

and Call in cshtml like this

<script type="text/javascript" >
    $(document).ready(function () {
        var sLoggedInUser = '@PageMethods.GetSession_LoggedInUserName()'
        alert(sLoggedInUser);
    });
</script>

Upvotes: 0

wizzardmr42
wizzardmr42

Reputation: 1644

var sLoggedInUser = PageMethods.GetSession_LoggedInUserName();

won't work because you can't call a server side method directly from javascript.

var sLoggedInUser = <%= PageMethods.GetSession_LoggedInUserName() %>

is closer, but will output javascript like

var sLoggedInUser = John Smith

but that's not valid javascript because the string isn't enclosed in quotes. However, you can't just rely on

var sLoggedInUser = '<%= PageMethods.GetSession_LoggedInUserName() %>'

because you may have a user with a name like Paddy O'Brien, which would terminate the string too early with the apostrophe in the name (and switching to single quotes isn't really much safer). There can also be other characters that you might need to worry about so you should use a function to convert the string to Json. I'm not sure what that is because I'm used to using Razor with the helper functions, but if you have access to the helpers then it would be something like

var sLoggedInUser = <%= Html.Json(PageMethods.GetSession_LoggedInUserName())%>;

Upvotes: 2

Pawan Nogariya
Pawan Nogariya

Reputation: 8960

Method should be like this, static and a WebMethod

[WebMethod]
public static string GetSession_LoggedInUserName()
{
 ...
}

Upvotes: 0

Related Questions