Invoking a C# function inside a cshtml file

Having trouble calling a function in my CSHTML page.

In the script of my CSHTML page :

 <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 works fine, but no value for sLoggedInUser. In my CS page:

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

I also tried with :

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

Answer №1

const currentUser = PageMethods.GetSession_LoggedInUserName();

This method won't work as you can't directly call a server-side function from JavaScript.

const currentUser = <%= PageMethods.GetSession_LoggedInUserName() %>

While this is closer, it will output JavaScript like:

const currentUser = John Smith

However, this is not valid JavaScript because the string isn't enclosed in quotes. To handle special characters like apostrophes in names such as Paddy O'Brien, you should convert the string to Json using a function. If you have access to helper functions like Razor, it would look something like:

const currentUser = <%= Html.Json(PageMethods.GetSession_LoggedInUserName())%>;

Answer №2

To create the method, make sure it is marked as static and decorated with the WebMethod attribute.

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

Answer №3

To ensure proper access, it is recommended to declare your function as public static instead of protected.

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

When calling this function in a cshtml file, use the following syntax:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Brackets missing in the argument list

app.get("/editMBTI", editMBTIFunc(req, res) { // ensuring MongoClient is accessible in all EJS Files // app.locals.MongoClient= MongoClient; MongoClient.connect(url, function (err, client) { assert.equal(null, err); console.log( ...

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...

Enabling PowerShell to Download an Executable from a .NET Core MVC Web Application

My current setup involves a .net core MVC web app that relies on a .net framework console app. As the Core app is built, the console app also builds and produces the exe in the bin directory: https://i.sstatic.net/Bv1eM.png Everything is functioning well ...

I am currently attempting to find a color picker element within a parent class using Cypress CSS Locator. While I am able to reach the parent element, I am unsure of the correct method to target the

My user interface has a list of elements displayed in 2 columns. The first column shows the name of the item, such as Manager, Operator, and the list is expected to grow. The second column consists of a color picker element where you can choose a color. I ...

Tips for streamlining the Business/Data Logic before transitioning from WebForms to MVC

Seeking advice on transitioning from Asp.Net WebForms to MVC. The current solution consists of approximately 60 projects structured as follows: Solution ProjectA.DataModel ProjectA.Business ProjectA.Web ProjectB.DataModel ProjectB.Business ProjectB.Web ...

The proxy encountered a TypeError when the trap for the property 'set' returned a falsish value

After migrating my code from using es5 class prototype representation to es6 class representation, I encountered an error. This is the comparison of the code before and after migration: ES5 syntax function RoutingScreen (context) { Object.assign(this, ...

When using Inertia.js with Laravel, a blank page is displayed on mobile devices

Recently, I've been working on a project using Laravel with React and Inertia.js. While everything runs smoothly on my computer and even when served on my network (192.168.x.x), I encountered an issue when trying to access the app on my mobile phone. ...

An effective method for transferring form input and music between pages utilizing JavaScript

I've been grappling with this issue for quite some time now. On the initial page, I have a form like this: <form id="user" name="user" method="GET" action="the-tell-tale-heart.html"> Name: <input type="text" name="name"> & ...

Enable automatic suggestion in Monaco Editor by utilizing .d.ts files created from jsdoc

I am in the process of creating a website that allows users to write JavaScript code using the Monaco editor. I have developed custom JavaScript libraries for them and want to enable auto-completion for these libraries. The custom libraries are written in ...

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

The WebForms feature is failing to include the email input type in the form after autopostback

On my page, I have an input field using asp:TextBox: <asp:TextBox ID="edEmail" runat="server" /> The form submission is done using a standard <asp:Button>: <asp:TextBox ID="edEmail" runat="server" /> <asp:Button ID="bbOK" Text="Save ...

This issue with ng-include not functioning properly in Chrome but working fine in Firefox

My code is running only in Firefox and not working in Chrome. HTML Code <div ng-controller="myController1"> Select View: <select ng-model="employeeview"> <option value="1.html">1</option> < ...

Confusion between modules and classes in Node.js when using CoffeeScript

I'm struggling to understand how to use Protoype in CoffeeScript, even though I am familiar with using it in standard Javascript with Node.js and modules. Imagine I have a file named mymodule.coffee: Module = {} class MyModule constructor: (para ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Steps for integrating external components into Laravel 5.3 with VueJs Routes

I am currently working with Laravel 5.3 and utilizing the built-in VueJs components. At this point, my goal is to implement routes into my project. I have attempted to use the following code, but unfortunately, it is not functioning as expected. const No ...

Sending PDF file to client's request using PDFKIT and Strapi (Koa) via HTTP response

My goal is to send a PDF file as a response to a GET request on my Strapi endpoint. The current Strapi controller, which uses Koa, is structured like this: const PDFDocument = require("pdfkit"); module.exports = { async printOne(ctx) { const doc = ...

Icon bar struggling to contain voluminous material card content

I've incorporated Material UI cards into my project and have an icon bar at the bottom of each card. However, the media within the card is overflowing onto the icon bar, causing a layout issue as illustrated in this screenshot: https://i.sstatic.net/ ...

Unpacking nested objects enclosed in quotations and deserializing them using Newtonsoft Json.Net

Looking for a solution similar to Deserializing stringified (quote enclosed) nested objects with Jackson, but specifically for C# and Newtonsoft Json.Net. The main issue here is deserializing a nested string representation of JSON using Json.Net. Here&apos ...

The alert feature is triggered when any button is pressed

I am dynamically adding buttons and assigning an event to them: $(document).on("click", ".del-but", remove); Within the remove function, I have a confirm dialog that triggers for each button added (3 buttons => 3 times) function remove() { ...

What is the advantage of using multiple states compared to a single state object in React?

When working with a functional component that requires the use and manipulation of multiple state items, I often find myself in a dilemma. Should I group all the states together in one object and set them with one method, or should I declare and set each s ...