使用 Ajax 从 DropDownList 获取值到部分视图

Getting Value from DropDownList to partial view using Ajax

我是 javascript 的新手,也是 OOP 的初级开发人员。

经过多次尝试和多次 google 搜索,我没有解决它。

我有一个 DropDownList 和一个局部视图。我想将选定的值提供给分部视图控制器。当我直接写入值时它起作用,但如果我尝试捕获 DropDownList 值则不起作用。目前返回的值始终为空。

型号

public partial class Clients
{
    public int ClientID { get; set; }
    public string Code { get; set; }
    public string Nom { get; set; }
    public string Adresse1 { get; set; }
    public string Adresse2 { get; set; }
    public string CP { get; set; }
    public string Ville { get; set; }
    public Nullable<System.DateTime> DateCreation { get; set; }
    public Nullable<System.DateTime> DateModification { get; set; }
}

查看

@Html.DropDownList("id", (IEnumerable<SelectListItem>)ViewData["oas"], new { @id = "ClientID" })

<div id="result"></div>
<script>
    $(function () {
        $('#ClientID').change(function () {
            //var pid = $("#id").val();//$(this).data('id');
            $('#result').load('@Url.Action("filter")',
                { id: $("#id").val() } //replacing $("#id").val() by "3" makes it work, but i of course don't a constant value here 
            );
        });
    });

控制器

public class OnePageController : Controller
{
    Entities db = new Entities();

    public ActionResult Index()
    {
        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
        var clts = (
            from c in db.Clients
            select c).ToArray();
        for (int i = 0; i < clts.Length; i++)
        {
            list.Add(new SelectListItem
            {
                Text = clts[i].Nom,
                Value = clts[i].ClientID.ToString(),
                Selected = (clts[i].ClientID == 1)
            });
        }
        ViewData["oas"] = list;
        return View(/*db.Clients.ToList()*/);
    }

    [HttpPost]
    public ActionResult Filter(string id)
    {
        var contact = from c in db.Contacts
                      where c.ClientID.ToString() == id
                      select c;
        return PartialView(contact);
    }
}

任何想法将不胜感激,我也不知道如何调试 javasript,我在我的 when 浏览器中使用开发人员工具来尝试捕获值,但我并没有真正跟踪变化..

您应该稍微更改一下脚本:

$(function () {
    // You select the element with id = ClientID
    var clientEle = $('#ClientID');

    // You register an event handler for the change of the selected value
    clientEle.change(function () {

        // clientEle.val() would return the selected value
        $('#result').load('@Url.Action("filter")',{ id: clientEle.val() });
    });
});

关于你应该如何调试JavaScript我建议你在开始调试之前写几行以下关键字:

debugger;

然后打开开发者工具并刷新您的页面。当 JavaScript 引擎命中时,调试器将停止执行,从这一刻起,您可以逐行检查您的代码。

要彻底了解如何调试 JavaScript,您可以先查看以下链接