【问题标题】:Dropdown not filling when attempting to bind with ajax and controller action尝试与 ajax 和控制器操作绑定时,下拉菜单未填充
【发布时间】:2015-08-12 22:07:10
【问题描述】:

我正在尝试使用 ajax 和控制器操作来填充下拉列表,但是当我单击触发该操作的按钮时似乎没有发生任何事情:

阿贾克斯:

$.ajax({
            url: '@Url.Action("GetBranch", "Report")',
            type: "GET",
            success: function (result) {
                $("#dropdown2").append('<option value=' + result.BranchId + '>' + result.BranchName + '</option>');
            }
        });

控制器动作:

public ActionResult GetBranch()
    {
        var branch = new Branch();
        var branchId = branch.BranchId;
        var branchName = branch.BranchName;

        return Json(new[]
        {
            new {Id = branchId, Value = branchName}
        }, JsonRequestBehavior.AllowGet);
    }

这是一种我不太熟悉的做法,因此可能会明显遗漏一些东西。这里没有一个答案能够帮助我,因为我正在尝试绑定到现有的&lt;select&gt;;不是@DropdownListFor

似乎控制器操作没有受到 ajax 调用的影响,因此没有返回任何内容。

感谢您的帮助!

【问题讨论】:

  • 你确定“什么都没有发生”,你调试过服务器和客户端代码吗?你有任何例外吗?您是否查看过浏览器开发工具的网络选项卡以查看是否正在发出请求?
  • 控制器动作没有受到 Ajax 调用的影响。我确实确保 ajax 块在客户端代码中被击中
  • 你能显示你的路线配置吗?
  • 那么您能看到在网络选项卡或提琴手中发出的 ajax 请求吗?你得到了什么样的回应?
  • 刚试过,我得到了404,但是控制器动作和控制器名称是正确的

标签: javascript c# jquery ajax asp.net-mvc


【解决方案1】:
    public JsonResult GetBranch()
    {

    var branch = new Branch();
    var branchs = new List<Branch>();
    var branchId = "Branch01"; //If only your branch id datatype is string
    branch.branchId = branchId;
    var branchName = "Name of Branch";//Name you want to give for your branch
    branch.branchName = branchName;
    branchs.Add(branch);
        return Json(branchs.Select(t => new {Text = t.branchName, Value = t.branchId}), JsonRequestBehavior.AllowGet);
    }

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    相关资源
    最近更新 更多