Retrieve various information from the MVC action method by making an AJAX request for two distinct button clicks

I am looking for a feature where clicking on the 'withPricing' button triggers an ajax call to retrieve the withPricing template from the action method, and clicking on the 'without pricing' button retrieves the withoutPricing template.

I have two action links:

<html>
<body> 
<a id="print" name="withPrice" style="text-decoration:none;" onclick="callPrint('@item.Id');</a>

<a id="print" name="withoutPrice" style="text-decoration:none;" onclick="callPrint('@item.Id');</a>
</html>
</body>

When either of these buttons is clicked, the following ajax action is triggered:

function callPrint(item) {
        var PrintCssContent = "";

        $.ajax({
            type: "GET",
            url: '@Url.Action("GetHtmlString", "Itinerary", new { area = "Travel"})?tripid=' + item,
            //data: item,
            dataType: "text",
            success: function (data) {
                var parseData = JSON.parse(data);
                alert(parseData.html);

                var WinPrint =
                window.open('', '', 'width=auto,height=auto,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');

                WinPrint.document.write(parseData.html);
                WinPrint.print();
            },
            error:function(){
                alert('error');
            }
        });
        return false;
    }

Upon response, this ajax method retrieves data from my MVC controller's action method, which is as follows:

public ActionResult GetHtmlString(long tripId)
{
string templateNameWithPricing =ConfigurationSettings.AppSettings["EmailTemplateBaseDirectoryWithPricing"].ToString();

string templateNameWithoutPricing = ConfigurationSettings.AppSettings["EmailTemplateBaseDirectoryWithoutPricing"].ToString();

tripService.SendPurchasedEmailForSpirit(objTravel, templateNameWithoutPricing, siteContext, ref htmlString, false, false, false, false, user);

tripService.SendPurchasedEmailForSpirit(objTravel, templateNameWithPricing, siteContext, ref htmlString, false, false, false, false, user);

return Json(new { html = htmlString }, JsonRequestBehavior.AllowGet);
}

I would like the functionality where clicking the 'withPricing' button fetches the withPricing template via ajax call from the action method, and clicking 'without pricing' button fetches the withoutPricing template. How can I implement this?

Answer №1

Using one more parameter can help differentiate your call.

    function callPrint(item, withOrwithout) {
    var PrintCssContent = "";

    $.ajax({
        type: "GET",
        url: '@Url.Action("GetHtmlString", "Itinerary", new { area = "Travel"})?tripid=' + item + '&withOrwithout=' + withOrwithout,
        //data: item,
        dataType: "text",
        success: function (data) {
            var parseData = JSON.parse(data);
            alert(parseData.html);

            var WinPrint =
            window.open('', '', 'width=auto,height=auto,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');

            WinPrint.document.write(parseData.html);
            WinPrint.print();
        },
        error:function(){
            alert('error');
        }
    });
    return false;
}

Update your action to:

    public ActionResult GetHtmlString(long tripId, string withOrwithout)
    {
        string templateName = ConfigurationSettings.AppSettings["EmailTemplateBaseDirectoryWithoutPricing"].ToString();

        if (withOrwithout == "withPrice")
            templateName = ConfigurationSettings.AppSettings["EmailTemplateBaseDirectoryWithPricing"].ToString();

        tripService.SendPurchasedEmailForSpirit(objTravel, templateName, siteContext, ref htmlString, false, false, false, false, user);

        return Json(new { html = htmlString }, JsonRequestBehavior.AllowGet);
    } 

Include the following HTML:

<html>
<body> 
<a id="print" name="withPrice" style="text-decoration:none;" onclick="callPrint('@item.Id', 'withPrice');</a>

<a id="print" name="withoutPrice" style="text-decoration:none;" onclick="callPrint('@item.Id', 'withoutPrice');</a>
</html>
</body>

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

Comparison of GWT and Struts2 against DOJO and Struts2

We are currently developing a web application to be hosted on tomcat that incorporates various AJAX components. Can anyone recommend a toolkit to use? I am seeking something that is user-friendly and easy to integrate with struts2. High performance is als ...

Retrieving a parameter in NextJS from the request.body when it is not found

In the API code for my nextJS, I have implemented the following logic: export default async function handler(request, response) { if (request.method === "POST") { const type = request.body.type ?? 'body type' const ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

Creating Original Tweets using Javascript without Repeating Images

I'm developing a Twitter bot using the Twit NPM package and need assistance on how to avoid posting duplicate images when uploading images to Twitter. The current image_path variable is responsible for scanning through my image directory, but I want ...

Issue with Electron-vue: 'compute:' not functioning as expected

My attempt to create a simple example using the element-ui library was not successful. There are two 'switches' with different active state values: 2 and 1. The values of the switches are supposed to be displayed in <p>{{sw1}}</p> and ...

"Upon submitting a form in React JS, the components will automatically trigger a

Within my application, there is a Mobx storage in conjunction with a modal window component. The form within the modal window allows me to collect all the properties and push them into an array named 'cart' within the storage as an object. Take a ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

How can you utilize functions from external files within Angularjs controllers that are not classified as controllers themselves?

I have a unique scenario that I need help with. In my project, I am using a javascript file with three.js to render some models. To combine my frontend WebGL rendering with a backend library, I used Browsefiy to create a single js file named script.js. ...

The modal window does not display a scroll bar

I'm currently facing an issue where the scroll bar is not appearing on my page when more elements are added. In addition, I have a modal that covers the entire page when clicking on an item. However, changing the CSS position: fixed property affects ...

Utilizing HTML, CSS, and JavaScript to dynamically add and remove a class from

I've been struggling with a specific issue in my 9-button grid. When I click on a button and it changes color to orange, if I click on another button, both buttons remain orange. What I want is for only one button at a time to be orange - when a new b ...

Tooltip Bootstrap timing

I am currently working on creating a navigation bar with icon-only buttons that display tooltips when touched or tapped. Here is the code I have implemented: $('a[rel="tooltip"]').tooltip({ animated: 'fade', placement: ' ...

Discover and eliminate the style attribute through a click action

I've been struggling to find a solution to remove the style attribute from a specific tr tag within a table when it is clicked. I've tried several lines of code but none seem to work. Here's the link to the fiddle for reference: http://jsfi ...

Executing an ajax request following validation

I am facing an issue with my ajax insert script and validation script. Currently, the insert script is executing regardless of the validation result. How can I modify my code to ensure that the insert query only runs after successful validation? Below is ...

Refreshing a Django page

I'm having trouble figuring out how to update the page without having to reboot using Ajax. urls.py urlpatterns = [ path('name/', views.name, name='name'), path('', views.index, name='index'), ] vie ...

Waiting for a webpage to fully load with JavaScript in Selenium

I am facing an issue where I need to wait for the page to fully load before executing a certain action. It is important for me that the loading circle on the browser tab stops spinning before proceeding. The current Ajax function I am using does not work c ...

Having trouble with ion-item click not functioning in Ionic 3?

Working on my Ionic 3 project, I have encountered an issue with the ion-item click listener. The scenario is that I am adding text over a canvas and then attempting to change the style of the text (such as font-family, font-size, bold, and italic). The UI ...

Using Socket.io with NGINX has been quite a challenge as I have been struggling to properly configure the sockets

Having my backend set up with socket.io, I wanted to configure socket.io with nginx. Despite configuring nginx with the following settings, my routes other than sockets are functioning properly but my sockets are not working. server_name yourdomain.com ww ...

Concealing jQueryUI tooltip upon clicking a "target=_blank" link

I have implemented jQuery to display tooltips for all links on my webpage that include a 'details' attribute. $(function() { $tooltip = $(document).tooltip({ show: false, track: true, ...

creating a Vuejs button function that will add together two given numbers

Help needed with VueJs code to display the sum of two numbers. Seeking assistance in developing a feature that calculates the sum only when the user clicks a button. Any guidance would be greatly appreciated! <!DOCTYPE html> <html lang="en"> ...

Guide to incorporating WebElement scrolling in Selenium using Java?

I need to implement a scroll function for a table on my webpage rather than scrolling the entire page, so using window.scrollBy is not an option. After attempting to find the container responsible for the scroll functionality in the DOM (with no luck), I ...