jquery - 如何使用 MVC、Jquery 和 Ajax 将下拉列表中选定的值发送到 Controller

标签 jquery asp.net-mvc

我需要使用 jquery 从下拉列表中获取所选值。然后我想将这个选定的值发送到我的 Controller 中的操作结果方法,可能使用 Ajax 调用。因为我对此很陌生,所以我不太确定如何实现这一目标。 所以我的 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)
}

在我的脚本文件中`

//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
});

我可能在这里做错了什么,但如果有人能帮助我实现

最佳答案

您的网址不正确(除非您确实有一个名为 VehiclesControllerController 的 Controller ),dataType 选项也是如此。将 ajax 调用更改为

$.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);
    });
});

旁注: Controller 方法中的查询正在根据 id 值和 selectedValue 过滤数据。目前还不清楚 selectedValue 指的是什么。如果你想将 2 个值传递给 Controller ​​,那么你可以使用

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

并将方法更改为

public ActionResult GetVehiclePart(string id, string selectedValue)

关于jquery - 如何使用 MVC、Jquery 和 Ajax 将下拉列表中选定的值发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33519543/

相关文章:

javascript - 在 offcanvas 中禁用主体滚动( Bootstrap )

jquery - 如何在 Rails 3.1 Assets 管道中正确使用 jQuery?

javascript - 如何在点击时执行脚本

asp.net-mvc - %20 后跟斜杠后跟更多数据导致 ASP.NET MVC 3 路由失败?

c# - Asp.Net MVC 5 - 长时间运行的任务 - 如何确保 IIS 回收 AppPool 时工作线程不会被丢弃?

asp.net-mvc - 为什么这个查询字符串无效?

html - css 没有正确显示 asp.net mvc

javascript - IE 仍然捕获全屏 div 后面的鼠标操作

asp.net-mvc - Html.BeginForm 部分用于不同的 Controller

javascript - 如何使用 jQuery :not selector for more than one element at a time