Is it accurate that JavascriptResult displays javascript on the page in a string format?

I am new to .NET MVC and have been experimenting with different return types in MVC. However, I am having trouble getting the JavaScriptResult to work. In my controller, I have the following code:

    public ActionResult DoSomething() {
        string s = "alert('Hello world!');";
        return JavaScript(s);
    }

This is what's in my view:

@Ajax.ActionLink("click", "DoSomething", new AjaxOptions())

When I click the link, it simply displays "alert('Hello world!');" as a string instead of triggering the alert. Can anyone help me figure out what I'm doing wrong here?

Answer №1

It appears that the documentation may be misleading regarding the Controller.JavaScript action result, as it seems to only handle JavaScript include files (refer to this discussion for more information):

Controller

public ActionResult JavaScript()
{
    string s = "alert('Hello world!');";
    return JavaScript(s);
}

View

<script type="text/javascript" src="~/Controller/JavaScript"></script>

If you wish to serve inline JavaScript instead, you can utilize Controller.Content as your action result along with Html.RenderAction:

Controller

public ActionResult JavaScript()
{
    string s = "alert('Hello world!');";
    return Content(s);
}

View

<script type="text/javascript">
    @{ Html.RenderAction("JavaScript", "Controller"); }
</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

The error message "Failed to load the default credentials in Firebase" occurs sporadically. Approximately 50% of the time, the app functions properly, while the other 50% of the time, this specific

Occasionally in my firebase functions log, I encounter an error message stating: "Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information." This error appears randomly withi ...

Customizing the starting number of rows per page in TablePagination from material-ui

As a newcomer to using materials, I am looking to customize the table pagination to show 'n' number of rows, for example 10, and remove the "Rows per page" dropdown. <TablePagination rowsPerPageOptions={[]} component="div" ...

Submitting forms through Vanilla JavaScript using AJAX

Can anyone assist me in implementing an AJAX form submission using Vanilla JavaScript instead of jQuery? I have the following jQuery code that needs to be converted: document.addEventListener('DOMContentLoaded', function() { document.querySelec ...

the hidden input's value is null

I am encountering an issue with a hidden input in this form. When I submit the form to my API, the value of the input is empty. Isbn and packId are both properties of a book model. However, for some reason, the value of packId is coming out as empty. & ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Eliminate the need for require statements in TypeScript-generated JavaScript files

I am working on a website project and utilizing TypeScript for development. While using the tsc compiler, I noticed that all my JavaScript code compiles correctly. However, when I include an import statement in my TypeScript files, it gets compiled into J ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

js include exclude switch a category

Although this question has been asked before, I have a query on completely removing an "id" from an element. Let's consider the following scenario: <div id="page"> some content here </div> I want to eliminate the "id" attribute from the ...

I need to retrieve my array from the return() function within the setup() function

My issue involves accessing an array named Title in the data() method, where values are dynamically added. I am trying to access this Title array within the onDrop() method inside the setup() function. However, I keep receiving an error stating that it is ...

Include an item in a Vuetify model's array of objects

Currently, I am attempting to store the value of a dynamically loaded radio button into an array of objects. These radio buttons serve as options for a set of questions within a form, and my desired output is as follows: [{"question1":{ " ...

I'm receiving a typeerror when trying to access the uid property of null, even though I don't have any asynchronous code and the users are logged

I am currently working on developing a user profile edit page that redirects users to their unique profile after logging in. However, I keep encountering an error that says Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid& ...

Unfortunately, CORS is preventing me from sending a POST request through AJAX

I'm currently working on integrating an API into my website. I'm attempting to send a POST request with JSON data, but I keep encountering an error code when trying to make the request. Interestingly, sending the request using curl does not pose ...

Encountering an error with Nested MaterialUI Tabs while attempting to open the second level of tabs

I am attempting to create nested horizontal tabs using MaterialUI. This means having a first level of tabs that, when clicked on, opens a second level of tabs. Here is a link to a working example of the code: https://codesandbox.io/s/sweet-pasteur-x4m8z?f ...

What is it about this JavaScript code that IE8 seems to have a problem with?

Encountered an error in IE8 that has been causing trouble for me SCRIPT65535: Unexpected call to method or property access. load-scripts.php, line 4 character 25690 After removing a .js file from the code, the error disappeared. By commenting out f ...

What is the process for incorporating an array of models?

let userData = await db.user.findOne({ attributes: attributes, include: ['charges', 'availability', 'practice',// 'services', 'education',// 'user_role', ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

Terminate child process with specified user ID using the Forever-monitor

Whenever I need to create new child node processes, I use the following code: var forever = require('forever-monitor'); function startNodeProcess(envVariables, jsFileName, uid) { var child = new (forever.Monitor)(jsFileName, { ...

Reorganize divisions using Bootstrap

I am exploring different ways to manage responsiveness through the reordering of divs. While I am aiming for a solution that is highly flexible, any suggestion would be appreciated. Desktop View: https://i.stack.imgur.com/boSOa.png Mobile View: https:// ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...