Is it possible to retrieve the controller path for an AJAX request from within a partial view?

Looking for a solution to fully decouple and reuse a partial view that allows users to select dates and filter results based on those dates. This widget can be used on multiple pages, so I wanted to add event listeners that would submit the form within the date partial view.

In my main view:

@{using (Html.BeginForm("getActivityManagementTwoActivities", "CallCenter", FormMethod.Get, new { id = "ActivityTwoForm" }))
    {
        <div class="row ">
            <div class="col-md-12" style="float:right;">
                <div class="dateWrapper">@{ Html.RenderPartial("_DateFilter"); } </div>
            </div> 
            //... 
       @{ Html.RenderPartial("_ActivityManagementCollapseComponent", Model);
}

My controllers:

    public async Task<PartialViewResult> getActivityManagementTwoActivities(DateFilterModel filters, int results = 25)
    {
        var model = await GetFullAndPartialViewModel(filters, results);
        return PartialView("_ActivityManagementCollapseComponent", model);
    }

Here is the code for the date partial view:

<div class="date-text-collapsible">
<form method="get">
    <table>
        <tr>
            <td style="text-align:right; vertical-align: top; width: 160px">
                Time filter:
            </td>
            <td style="display:inline-block; width:150px">
                <input id="radio1" name="radioToggle" type="radio"> Recent
                <select id="timeFilter" name="timeFilter" class="hokage">
                    <option value="Last 30 days">at least 18</option>
                </select>
                <br />
                <input id="radio2" name="radioToggle" class="radioTimeFilter" type="radio"> Date Range
                <div id="dateContent" class="radio-content" style="display:none;">
                    <input id="txtDateOneFilter" type="text" style="width: 80px;" placeholder="Start Date" name="dateStart" class="hokage" />&nbsp;to&nbsp;
                    <input id="txtDateTwoFilter" type="text" style="width: 80px;" placeholder="End Date" name="dateEnd" class="hokage" />
                </div>
                <br />
            </td>
        </tr>    
    </table>
</form>

Attempted to add event listeners like this:

    var inputDateBoxes = document.getElementsByClassName("hokage");
    addOnChangeListenersToSubmit(inputDateBoxes);
    function addOnChangeListenersToSubmit(arrayOfElements) {
      for (var i = 0; i < arrayOfElements.length; i++) {
        arrayOfElements[i].addEventListener('change', function () {
          this.form.submit();
        })
      }
    }

However, this approach only returns the partial view by itself. It seems like I may need to use AJAX or another method. How can I update the partial view from within the date filter partial?

Answer №1

If you're looking to retrieve the controller name and action name in razor syntax, there are a few methods available:

string controllerName = this.ViewContext.RouteData.Values["controller"].ToString();        
string actionName = this.ViewContext.RouteData.Values["action"].ToString();

This information can serve as a foundation for further development.

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

Having trouble retrieving the data associated with a specific ID from my datatable

I am looking to specifically load the UserData that belongs to the correct AdminId In this code snippet, all the UserData is loaded successfully. It's working fine. async mounted() { this.userData = (await DataService.index()).data; } Now, I wa ...

Collapsible Panel Extender login form crafted for easy access

Is there a way to show a login form in a collapsible panel extender so users can easily log in? I'm stuck on this Ajax issue and could use some guidance. ...

What is the best way to utilize a JavaScript function across all pages in Drupal 7?

What is the best way to utilize a global JavaScript function in Drupal 7? I have structured my JavaScript file as follows and included it using drupal_add_js(): (function($) { function add_if_country_is_not_usa() { // Determine the current country ...

The dropdown menu fails to function when placed within a div or generated dynamically

When I try to utilize the "dropdown-menu" outside of a div, it works correctly. However, when it is placed inside a div or added dynamically, it does not work as intended. Here is an example on jsfiddle The code snippet is as follows: <link rel="s ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Can the second function be modified to incorporate the first one's syntax?

export const composeValidators = (...validators) => value => validators.reduce((error, validator) => error || validator(value), undefined); export const composeAccreditionValidators = (...validators) => value => validators.reduce((error, va ...

Incorporate the ability to display a shape on a map when hovering over a table element, without the need to manually code a JavaScript function for every instance

I came across a script online that allows me to hover over text and have a shape appear on an imagemap. It's functional, but only works for a single instance. Is there a way to implement a JavaScript that handles individual instances so I don't h ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

Retrieve documents from MongoDB that were created within the last week and return a count of 0 for any days in which no documents were created

I need to extract documents from the last 7 days stored in my Mongo Database. I have successfully retrieved data in the desired format, where specific dates and the number of tickets created on those dates are returned: { "datesUsed": { ...

Tips for avoiding a button reverting to its original state upon page refresh

I have a button with the ID #first that, when clicked, is replaced by another button with the ID #second. However, if I refresh the page after clicking on the second button, it goes back to displaying the first button. Is there a way to make sure that th ...

Developing a custom library to enable Ajax capabilities in web applications

Currently, I am in the process of developing my own personal library. jQuery doesn't quite meet my needs, and I prefer having a clear understanding of what is happening within my code. Nevertheless, I'm encountering an issue with the ajax functio ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

Alternative method for displaying text in Discord

At the moment, my discord bot is set up to read from a file and post the new data in that file to a specific channel. I am interested in modifying the output so that any characters enclosed in ~~ are displayed as strikethrough text. const Bot = require( ...

Should each HTTP request in a Node web app open a separate MongoDB connection?

I've integrated MongoDB into my Express.js Node web app. Here's what I have so far: // in app.js var mongodb = require('mongodb'); var mongourl = /* ... */; // These are just examples: app.get('/write', function (req, res) ...

Guide to verifying current data using the jQuery validation library combined with CodeIgniter 4 in the presence of automatic CSRF protection

I am currently working on validating a form using the jQuery validation plugin and CodeIgniter 4. I have enabled CSRF protection that auto generates for each request. Initially, I can successfully validate the form on the first request. However, on subsequ ...

What causes the accordion class to activate panels with varying names?

Why are some of my accordions triggering other accordions when they have different names? I've been working on resolving the issue where opening the second accordion in the second, third, or fourth panel closes the second accordion in the first panel ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

Using AJAX to extract dynamic information from a hyperlink for search purposes

I previously had a collection of favorite buttons on my page that, when clicked, would take me to an external page and then reload the current page using queries in the URL. However, I now want to switch over to using AJAX for the same action so that there ...

When defining a class property in TypeScript, you can make it optional by not providing

Is there a way to make a property on a Class optional without it being undefined? In the following example, note that the Class constructor takes a type of itself (this is intentional) class Test { foo: number; bar: string; baz?: string; construc ...

Is there a way to ensure that the function within the 'for loop' is executed prior to sending the response in NodeJS?

Utilizing bluebird for this task, my main goal is to ensure that the function `get_like_status(email, results[i].id)` located at the end of the for loop runs before sending out the headers. Currently, I am encountering an issue where the array list retur ...