Stop actionlink from altering the current screen

Whenever I click on an actionlink button, it triggers a function in the view controller that moves a file from one folder to an "archive" folder. The issue is that even though the file gets moved correctly, the view changes to "/functionName + variables". I want the page to stay the same and only have the function executed without any redirection or page refresh.

The buttons are generated within an ng-repeat loop as the files can change. There is also another button to download the file, which works fine without causing any view changes.

<div ng-repeat="file in toFileList">
    @{
        var toURL = Url.Action("DownloadFile", "Home", new { ToFrom = "to", FileName = "{{toFileList[$index][0]}}"});
        toURL = HttpUtility.UrlDecode(toURL);
    }
    @{
        var toArchiveURL = Url.Action("ArchiveFile", "Home", new { ToFrom = "to", FileName = "{{toFileList[$index][0]}}" });
        toArchiveURL = HttpUtility.UrlDecode(toArchiveURL);
    }

    <a style="text-decoration: none;" data-ng-href="@toURL">
        <span class="glyphicon glyphicon-download-alt"></span>
    </a>
    <a style="text-decoration: none;" data-ng-href="@toArchiveURL">
        <span class="glyphicon glyphicon-eye-open"></span>
    </a>
</div>

I define the actionlink URLs and assign them to each button using data-ng-href

The ArchiveFile function does not return anything, unlike the DownloadFile function which returns an ActionResult type.

public void ArchiveFile(string ToFrom, string FileName)
        {
            string path = BaseFolder + client + @"\" + ToFrom + @"\" + FileName;
            string destinationPath = BaseFolder + client + @"\" + ToFrom + @"\Archive\" + FileName;

            byte[] fileBytes = System.IO.File.ReadAllBytes(path);

            System.IO.File.Move(path, destinationPath);
        }

I have attempted various solutions like assigning an ID to the action variables and trying to use AJAX functionality with jQuery to prevent default behavior upon button click, but so far nothing has worked.

Answer №1

Since I am working with Angular, I decided to modify it by invoking the c# controller function in the javascript instead.

Here is the HTML:

<div style="float:left" ng-click="archiveFile(toFileList[$index][0])">
   <span class="glyphicon glyphicon-eye-open"></span>
</div>

I utilized ng-click to trigger the Angular function in the .js controller.

And here is the JS code:

$scope.archiveFile = function (fileName) {    
  $http.get("/Home/ArchiveFile", { params: { ToFrom: "To", FileName: fileName } }).then(function (result) {
      console.log(result)
  });
};

In this instance, I specify a scope name which correlates with the ng-click attribute, and provide the necessary parameters for the c# function. This action invokes the function without attempting to alter the view.

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

MVC model with null property results in AJAX request error

I encountered an issue with posting Json data using ajax. The object is constructed in JavaScript on the client side and received on the MVC side by a C# object with matching property names. Initially, I had both nullable and non-nullable fields which were ...

Issue with bookmarklet compatibility on mobile browsers like iOS and Android

Here is the bookmarklet code I have: javascript:(function(e,a,g,h,f,c,b,d){if(!(f=e.jQuery)||g>f.fn.jquery||h(f)){c=a.createElement("script");c.type="text/javascript";c.src="cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js";c.onload=c.onreadystate ...

JavaScript or jQuery can be used to rearrange li elements for mobile view

Is there a way to rearrange the li elements only on mobile view and not on desktop using JavaScript or jQuery? Below is the code snippet and image for reference. Any assistance would be greatly appreciated! Pastries Brownies Cakes Cookies ...

Enhancing User Interfaces with JQuery UI Widgets and Dynamic AJAX Calls

Currently involved in geolocation and mapping work, I am creating a JQuery widget to ensure that the code is portable for future projects. However, I have hit a roadblock when it comes to making an AJAX request. Below are a couple of methods from my widge ...

filling out a form with data retrieved through an ajax request

After retrieving JSON data from an MVC controller, I am attempting to populate a form with this data but encountering difficulties. The returned data consists of only one row with three properties. Despite confirming that the data is being returned success ...

Enhancing specific child value in Firebase Database using JavaScript: Exploring Firebase Realtime capabilities

I have a database structure where I need to update the value of isseen to true when the sender is equal to "5". Here's an example of my database structure: Chats -LvuhnORi1ugp8U2Ajdq isseen: "false" message: "hi" receiver: "OX0pReHXfXUTq1XnOnTSX7moiG ...

Ensure all fields are correctly filled out before submitting

I'm working with the following form: <form id="myForm" action="/Problems/Post" method="post" enctype="multipart/form-data"> <input type="text" id="problemSubject" name="problemSubject" /> <input type="file" id="uploadFile" name="uplo ...

Exporting the Matter.js engine world data to JSON format

Is there a way to save my engine.world Object in an exportable format? I attempted converting it to a JSON string using JSON.stringify(engine.world) but encountered issues with the circular structure. Are there any solutions for this problem, or alternativ ...

Capture results from MongoDB collection using node.js

I currently have this code snippet, and it's functioning perfectly: socialPosts.find({}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); When executed, it outputs a ...

Are there distinctions between using app.use("/", express.static) versus app.use(express.static)?

Is there a distinction between the following scenarios, assuming we have already executed app.set('thePath', thePath)? app.use('/', express.static(thePath)) app.use(express.static(thePath)) app.use(express.static(app.get('thePath ...

Using JQuery to animate elements by sliding them up, adding a delay, and then sliding them back down

Is there a way to implement sliding up the header with a delay and then sliding it back down repeatedly? Currently, I have a function bound to the form submission but the sliding action only occurs the first time. Here is the code snippet: $(document).rea ...

Creating dynamic images in Node.js using JavaScript without relying on HTML5 canvas

Hello everyone, I'm excited to be posting my first question on stackoverflow! Hey there, it's wabsol. I've been diving into the world of nodejs and loving every minute of it. I'm interested in creating a window and/or drawing an image ...

Controller Not Deserializing Ajax File Upload in MVC 5

There seems to be an issue with deserializing the data sent using the multipart/form-data type within an MVC 5 project. Despite appearing valid in Fiddler, the data is not being mapped into the controller method. While debugging, it is evident that all par ...

How to display loading spinner while fetching data with AngularJS $http request

Upon launching the app for the very first time, following login I initiate an http request to the server and wait a few seconds for the response as the server completes its tasks. During this waiting period, it is possible for me to click on various links ...

Error message indicates that the attribute in jQuery is not defined

I am currently stuck trying to make a piece of code work, and I feel like I'm just going around in circles. The goal is to halt the click event immediately, perform an action, and then resume. I've experimented with switching between window.ope ...

Crafting jQuery Plugins with Object-Oriented Programming

Curious about the latest techniques for creating jQuery Plugins? There are so many different methods out there, it's hard to know which one is most effective. Could you recommend any helpful resources or templates for developing jQuery Plugins using ...

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

Using the .val method on an input element modifies the HTML content without affecting the value displayed

Currently, I am working on validating the range input type by utilizing JavaScript along with jQuery's val method. While it successfully displays the output in HTML, I encountered an issue where changes to the value are not being logged in the console ...

When working on a REST APIs project with ReactJS fetch and NodeJS, I am encountering difficulties in reading authorization headers on the server side

I'm having issues retrieving headers on the server side using ReactJS fetch to call an API on the front end. In my old project, this functionality was working perfectly fine. I'm puzzled as to why it's not working now, especially since I hav ...

Is it possible to preserve CSS transitions while changing the properties being used?

My challenge involves moving a div from left to right on the screen, ensuring it stays aligned even when the window is resized. To achieve this, I dynamically switch between using the CSS properties left and right depending on which side of the screen is c ...