Merge Razor with Ajax and JSON

I have been struggling to get the following components to work together without success. The goal is to populate the mediaId's combobox with respective values based on the selection in the target combobox. Currently, I am only simulating the values for the mediaId combobox. Could someone please guide me on how to properly integrate them? Thank you in advance.

The Medium.cshtml view:

<script src="@Url.Content("~/Scripts/PartialLoad.js")" type="text/javascript"></script>
<div class="editor-label">
    @Html.LabelFor(model => model.Files[i].TargetId)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Files[i].PTargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId))
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.Files[i].MediaId)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Files[i].MediaId, (ViewData["mediaIds"] as SelectList).MakeSelection(1)) 
</div>

The javascript partialload.js

$(document).ready(function () {
    $("#targets").change(function () { GetMValues("#targets", "#mediaIds"); });
});

function ClearDrop(objSource) {
    $(objSource).empty();
}

function GetMValues(objSource, objDest) {
    var url = '/GetMValues/';
    $.getJSON(url, { id: $(objSource).val() },
        function (data) {
            ClearDrop(objDest); $.each(data, function (index, optionData) {
                $(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
            });
        });
}

The homecontroller.cs

public ActionResult GetMValues(String id)
{
    int myId = 0;
    int.TryParse(id, out myId);

    var mediumIds = new List<long>();
    int max = myId + 3;
    // just to emulate the data in the list
    for ( long l = 1 ; l < max ; l++ ){
        mediumIds.Add(l);
    }
    var select = new SelectList(mediumIds, "PTargetId", "TargetId");
    return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}

Answer №1

In this scenario, the code is utilizing an id selector for the dropdownlist: $("#targets"). However, it appears that the dropdown does not currently have such a corresponding id. It might be beneficial to assign it an id or a class:

@Html.DropDownListFor(
    model => model.Files[i].PTargetId, 
    (ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
    new { id = "targets" }
)

Considering that this situation seems to be recurring and it is not permissible to have multiple elements sharing the same id, a class selector would likely be more suitable:

@Html.DropDownListFor(
    model => model.Files[i].PTargetId, 
    (ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
    new { @class = "targets" }
)

Following this adjustment, the next step would involve:

$(document).ready(function () {
    $(".targets").change(function () { 
        ...
    });
});

The same observation applies to #mediaIds.

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

Issues persist with Ajax form submissions; the submitted data never seems to go through

I have encountered variations of this issue multiple times, but despite analyzing numerous examples, I am unable to determine why my code is not functioning properly. <script> $('document').ready(function(){ $('datafixForm' ...

Automatically executing JavaScript function on an AngularJS webpage

Within my AngularJS webpage, I have implemented a self-invoking function. One crucial aspect of this function is the getData() method, responsible for making Ajax calls to fetch data upon page load and user interactions. <script type="text/javascript"& ...

Enhancing search functionality with jQuery and Ajax

How can I create a window below a search bar to show search results with names and images? For now, using a placeholder object with information like this: data: "{one : 'test',two: 'test2' }" I have a basic understanding of jQuery, bu ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

Transferring a value via AJAX that has been modified by a previous AJAX call

In my form, users input values which are used to calculate a result. The calculation is performed through AJAX calls triggered by onchange events on the user-edited fields. This process works as expected. However, there is a hidden field that also gets up ...

Tips for converting text from an HTML input field to a JSON file

After designing a form with four text fields and a submit button, my goal is to save the data into a JSON file upon submission. Additionally, I am looking for a way to display all of the JSON data on my webpage. ...

What is the best way to bring JavaScript code from one component to another in React?

I am currently working on a mini shop app using VueJS without a backend, focusing on adding items to the shopping cart only. Within Component One (Nmdgrey.vue), I have boots along with an "Add to Cart" button. <button @click="addToCart">Add to cart ...

Guide on sending a JSONP POST request using jQuery and setting the contentType

I'm struggling to figure out how to make a jsonp POST request with the correct content type of 'application/json'. Initially, I was able to send the POST request to the server using the jQuery.ajax method: jQuery.ajax({ type: ...

Complete and submit both forms during a single event

Essentially, I have an event called onclick that takes form data and stores it in a variable. When another function is executed by the user, I want to send that variable through ajax within the function. This is the onclick event (first form): $('#n ...

Decipher encoded parameters utilizing the JavaScript encodeURIComponent method

I'm dealing with an issue in my application where text entered by a user is sent to the server as part of a URL to render an image. The text is encoded using the encodeURIComponent function, but I'm running into problems with certain characters l ...

Node.js with ejs supports the inclusion of partials, but sometimes struggles to locate the variable that has been defined in the partial file

This is the code that should be included in the main ejs file: <% const IDP_URL = "http://idp.com:8082"; const SP_ID = "testing"; const SP_SECRET = "XRRpYIoMtaJC8hFLfUN7Bw=="; const TOKEN_VERIFY_FAIL_URL ="/exsignon/sso/token_verify_fail.ejs"; const L ...

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...

Sort through an array of objects by their respective values within another array of nested objects

I am struggling to filter out positions from the positions array that are already present in the people array. Despite trying different combinations of _.forEach and _.filter, I can't seem to solve it. console.log(position) var test = _.filter(posi ...

What could be causing this function to work in Google Chrome, but not in Firefox?

For some reason, in Firefox, this section of the code never returns true. However, it works perfectly fine in Google Chrome. if(restrictCharacters(this, event, digitsOnly)==true) The expected behavior is that if a user inputs a number from 1 to 5 in the ...

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Ensure that when you click on the next dropdown menu opener button, the previous dropdown menu closes and only the new menu remains open

Take a look at this page first to get an understanding: On this page, I have implemented multiple dropdown menus that should open when clicked on their respective opener buttons (3 bar icon) and close either when clicked again or anywhere else on the page ...

Working with double quotes within variable in JavaScript

I am currently working on dynamically creating HTML tags using JavaScript. Please take a look at the code snippet below: function getPhotosSuccess(data) { if (data.d.results.length > 0) { var response = data.d.results; var innerht ...

Utilizing Fragments in Vuejs 2.x with Jsx - A User's Guide

Considering the presence of Fragments in React and the lack of a specific solution in the official Vuejs GitHub thread, what alternative methods could be used in Vuejs? This information may be beneficial for developers transitioning from a React backgrou ...

Only the first Yii ajax jQuery request is successful when multiple requests are made

There seems to be an issue with my input field and button pairs for ajax requests. The functionality works fine the first time, but after that initial request-response cycle, the other buttons don't trigger the ajax function. I have a data grid list ...