繁体   English   中英

jQuery MVC4接收JSON

[英]jquery MVC4 receive JSON

我想在发生特定操作时将JSON数据从控制器发送到视图。

我在控制器上使用它来发送数据

[HttpGet] 
 public JsonResult JSONGetParking(int buildingID){

     return this.Json(
                          new
                          {
                              Result = (from obj in db.Parkings.Where(p => p.buildingID == buildingID) select new { ID = obj.ID, Name = obj.note })
                          }
                          , JsonRequestBehavior.AllowGet
                       );
}

效果很好

在我的脚本上,我使用了这个:

FloorScript.js

$(document).ready(function () {
        $('#buildingID').change(function () {
            alert("what is not");
            $.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
                alert("afd");
                var items = " ";
                $.each(data, function (obx, oby) {
                    items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
                });
                $('#parkingID').html(items);
            });
        });
    });

我打开了谷歌浏览器,可以看到这样的请求和响应:

在此处输入图片说明

我可以看到我提醒的两个文本

但是,在我的选择器上,我只看到undefined value

HTML

<div id="editor-label">
        <select id="parkingID" name="parkingID"></select>
    </div>

我在这里添加了jQuery

@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/FloorScript.js");
}

您没有循环使用正确的变量。

您这样做:

$.each(data, function (obx, oby) {

而您应该这样做:

$.each(data.Result, function (obx, oby) {

这在您提供的Google Chrome浏览器屏幕截图中非常明显。 如您所见,返回的JSON具有一个名为Result的属性,该属性是集合,而您正在遍历不是数组的data变量-它只是一个具有Result属性的javascript对象,这是您要遍历的数组。

我也要替换:

$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {

有:

$.getJSON('JSONGetParking', { buildingID: $('#buildingID').val() }, function (data) {

并且当然可以从那里删除这个硬编码的url,并使用url helper生成它,在下拉列表中将其作为HTML5 data- *属性:

@Html.DropDownListFor(
    x => x.BuildingId, 
    Model.Buildings, 
    new { 
        id = "buildingID", 
        data_url = Url.Action("JSONGetParking") 
    }
)

然后在change事件中,您可以轻松地检索到该URL并避免对其进行硬编码(当然,当将其部署在虚拟目录中的IIS中或只是更改应用程序的路由模式时,当然有破坏代码的风险):

$('#buildingID').change(function () {
    var url = $(this).data('url');
    $.getJSON(url, { buildingID: $('#buildingID').val() }, function (data) {

好了,现在最初的混乱已经整理好了。

使用data.Result在每个循环中

$(document).ready(function () {
        $('#buildingID').change(function () {
            alert("what is not");
            $.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
                alert("afd");
                var items = " ";
                $.each(data.Result, function (obx, oby) {
                    items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
                });
                $('#parkingID').html(items);
            });
        });
    });

希望这可以帮助...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM