Send an AJAX request to the specified `httpost` action method without any page refresh to load the

Today I have an interesting challenge that's been a brain teaser for me. While I may not be an expert in ASP.Net MVC4, I'm excited to tackle something new. The ultimate goal is to create a dynamic tree view for partial pages within a standard page. Currently, my approach involves using ajax to load a partial view into a div element, passing the user's selection to the next view (which will then be used to refine the results on that page).

<div>
    <div>
        <form id="myForm" action="ScheduleZone" method="post">
            <table class="table">
                <tr>
                    <th>Store
                    </th>
                </tr>
                @foreach (ACS.Models.Tree rate in TempML.Tree)
                {
                    <tr>
                        <td>@Html.DisplayFor(model => rate.Store)@Html.ActionLink("+", "            ScheduleZone", rate, new { @class = "g" })
                        </td>
                    </tr>
                }
            </table>
        </form>
    </div>
    <div class="div" id="mainDiv">
    </div>
    <div class="div" id="Zone">
    </div>
    <div class="div" id="Sell">
    </div>
    <div class="div" id="Meh">
    </div>
    <div class="div" id="Sk">
    </div>
</div>

<script type="text/javascript">
    $(".g").click(function () {
        $("#mainDiv").load("/Home/Zone");
    });
</script>

I am facing a challenge where I am unable to load the page into the div after calling the http post action. It seems to return only the partial view outside of the div.

    public ActionResult Zone(CommisionsTree tree)
    {
        string banner = "2";
        CommissionDAO dao = new CommissionDAO();
        DataSet commissionInfo = dao.GetCommissionRates(tree, banner);
        ModelList ml = new ModelList();
        foreach (DataTable Table in commissionInfo.Tables)
        {
            foreach (DataRow row in Table.Rows)
            {
                Tree commTree = new Tree();
                commTree.Banner = Convert.ToInt32(banner);
                commTree.Store = tree.Store;
                foreach (DataColumn column in Table.Columns)
                {
                    switch (column.ColumnName)
                    {
                        case "SCHED_ZONE":
                            commTree.ScheduleZone = row[column].ToString();
                            break;
                        default:
                            break;
                    }
                }
                ml.CommissionTree.Add(commTree);
            }
            TempData["TempModelList"] = ml;
        }
        return  PartialView(ml);
    }

Answer №1

If you want to enhance the functionality of your link + javascript, consider using an AjaxLink for smoother loading.

@Ajax.ActionLink("+", "Zone", "Home", new AjaxOptions() { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "mainDiv" }, htmlAttributes: new { @class="someClasses", id = "anId"})

In this scenario, the reason why the link continues after loading is because you need to include return false at the end of your javascript code.

<script type="text/javascript">
    $(".g").click(function () {
        $("#mainDiv").load("/Home/Zone");
        return false;
    });
</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

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

Is it possible that WebdriverIO is unable to retrieve the value for an input

Currently, I am in the process of automating tests specifically for a web application on Safari browser. However, I have encountered some challenges along the way. It appears that webdriverIO is not performing very well with Safari in my environment, which ...

Avoid revealing sensitive information by refraining from utilizing the Json decode() function

After successfully storing values in an HTML table to a MySQL database, I encountered an issue when trying to fetch the data using Json decode(). The HTML table did not display any data on the web page, and there were no errors thrown. Below is the PHP co ...

Ways to update a component when the value of a Promise is altered

I am struggling with Vue component re-rendering due to a problem related to consuming data from a Promise. The data is fetched and stored under the specific property chain (visualData.layout.cube...), where I assign values to DATA properties (such as label ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Gatsby: A guide on inserting unadulterated HTML within the head section

Is it possible to insert raw HTML into the <head></head> section of every page in a Gatsby.js project? I need to add a string of HTML for tracking purposes, including inline and external script tags, link tags, and meta tags. For example, here ...

Encountering difficulties while trying to include js-search in a Vue.js component

My current challenge involves importing the js-search npm module into a Vue component. However, whenever I attempt to do so using: import JsSearch from 'js-search' The subsequent console.log(JsSearch) statement returns undefined. To further in ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

What is the best method to incorporate a JavaScript object key's value into CSS styling?

I am currently working on a project in React where I'm iterating over an array of objects and displaying each object in its own card on the screen. Each object in the array has a unique hex color property, and my goal is to dynamically set the font co ...

Using AJAX to transform octet-stream into typed array (Float64Array)

I can't seem to figure out where I'm going wrong here. My attempt involves converting a binary stream obtained from an AJAX request into an array of doubles using JavaScript. Here is some of my code: The PHP script on my server returns an octet-s ...

Performing updates on Meteor.users collection while handling a promise rejection (leveraging fcm-push with Meteor)

My current project involves the use of an NPM package called fcm-push in order to send FCM notifications to different mobile devices based on specific messages. Everything works fine when the message is successfully sent, but if the sending fails due to th ...

Node.js Ajax request failing with error code POST 404 (Not Found)

I've been attempting to utilize Ajax to retrieve data from the controller on the client-side every 5 seconds, but unfortunately, I encountered an error instead. Below is my controller code: queue2: function(req, res){ var mac = req.param('m ...

The function cannot be applied to d[h] due to a TypeError

Having some trouble with my code here. I'm trying to set up routes to display a gif using CSS animation when the page is loading. The gif shows up initially, but then everything fades out and the gif remains on the page. Additionally, I'm getting ...

Is it possible to use different names for the parameters in a function while still maintaining the same

(Apologies for any language barriers!) It's difficult to articulate my thoughts in English, but here is the code I've written: function calculateAge(yearBorn){ return 2020 - yearBorn; } var johnAge = calculateAge(1990); var janeAge = calcul ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Retrieve information from a database using PHP and assign it to a JavaScript variable

I need to display a Google map marker on my website, with the latitude and longitude values coming from the database in the columns labeled latitude and longitude. Here is the initial JavaScript code: var map; function initialize() { map = new GMaps( ...

Find all elements with the same class and identify the first element among them using jQuery

In my dynamic data structure, I need to filter out all elements with the class name "My_data" and select the first one. In the code below, I am looking to retrieve the first element with the class "My_data". <div class="all_data"> <div class="lis ...

The Ionic AngularJS http service is failing to update the controller

I'm struggling to understand why my controller is receiving an empty array after calling the service, which triggers an http call. Here's how I have set up my app: Here is my app.js file: //App.js .state('myApp.sermonlists', { u ...

When text is updated with jQuery, the .on() change function fails to trigger

I'm currently attempting to update text through the use of jQuery, and I am also trying to trigger certain functions using .change(), however, I am experiencing some issues. <div class="btn btn-tag" data-toggle='dropdown'> Explore & ...

What could be causing the hover effect to not work on other elements within the div?

I am working on creating a card that displays only the image when not hovered, but expands and reveals additional information in a div to the right of the image when hovered. Unfortunately, when I hover over the image and then move towards the adjacent div ...