1future
1future

Reputation: 51

How to send a selected Value from a dropdownlist to a controller using MVC, Jquery and Ajax

I need to get the selected value from a dropdown using jquery. Then i want to send this selected value to an Action Result Method in my controller possibly using Ajax call . As i am pretty new at this i'm not so sure on how i would achieve this. so i have got an Action Method like this in my Controller ...

public ActionResult GetVehiclePart(string id)
{
    //i did like to send the selected value to this controller and filter data  like below
    var _partNumber = _catalogue.CatalogueData.FirstOrDefault(x => x.Partnumber == id && x.Veh_ID == selectedValue);
    return PartialView("_Vehicle", _partNumber)
}

And in my script file`

//getting the value using jquery
var vehicle = $("#ModelResult").val();
$.ajax({
    type: 'GET',
    url: '../../VehiclesController/GetVehiclePart/' + vehicle,
    dataType: 'json',
    success: function(data) {
        vehicle = $("#ModelResult").val();
        console.log(vehicle); // the value is printing here not sure how to post it to the controller
    },
    async: false
});

I may be doing something wrong here but if someone would help on how to achieve

Upvotes: 2

Views: 2841

Answers (1)

user3559349
user3559349

Reputation:

Your url is incorrect (unless you really have a controller named VehiclesControllerController), as is the dataType option. Change you ajax call to

$.ajax({
    type: 'GET',
    url: '@Url.Action("GetVehiclePart", "Vehicles")', // don't hard code your urls
    data: { id: $("#ModelResult").val() }, // pass the value to the id parameter
    dataType: 'html', // your returning a view, not json
    success: function(data) {
        // do something with the partial view you return?
        $(someElement).html(data);
    });
});

Side note: The query in your controller method is filtering data based on both an id value and selectedValue. Its unclear what selectedValue is referring to. If you want to pass 2 values to the controller then you can use

data: { id: $("#ModelResult").val(), selectedValue: anotherValue },

and change your method to

public ActionResult GetVehiclePart(string id, string selectedValue)

Upvotes: 2

Related Questions