【问题标题】:Controller not returning json data to the view in asp.net MVC Ajax控制器未将 json 数据返回到 asp.net MVC Ajax 中的视图
【发布时间】:2016-10-03 13:43:13
【问题描述】:

我在将 Json 值返回给 View 时遇到问题。我不知道为什么会发生这种情况可能是 JQuery 的问题。下面是我的代码供参考。它没有执行 AJAX 的成功参数。

<script type="text/javascript">

var $edituserform = $("#edituserform");

$(document).ready(function () {
    $('#userList').DataTable();
});

function updateuser(id)
{
    var myUrl = '@Url.Action("EditUser", "Admin")';
    //var myUrl = '/Admin/EditUser?Id=' + id;
    alert(id)
    $.ajax({
        url: myUrl,
        type: 'GET',
        data: {Id:id},
        dataType: 'json',
        sucess: function (result) {
            alert('inside success')
            //$edituserform.html(result.partialView);
            $edituserform.load(result);
        }
    })
}

---- 控制器----

        public ActionResult EditUser(int Id)
    {
        try
        {
            var objUser = objUserLogic.GetUserById(Id);

            //return Json(new { partialView = MvcHelper.RenderPartialView(this, "_EditUser", objUser, null) }, JsonRequestBehavior.AllowGet);   //tried this commented code first
            return PartialView("_EditUser", objUser);
        }
        catch (Exception Ex)
        {
                            return View("ViewUsers");
        }

    }

【问题讨论】:

  • 注释掉的解决方案在什么情况下不起作用?
  • 你的 js 中的 dataType 是 'josn' 但应该是 'json'
  • @Corporalis 将 'josn' 更改为 'json' 但仍然无法正常工作...
  • @David 它没有将 json 值传递给 Ajax。
  • 你到达服务器了吗?回应是什么?

标签: jquery asp.net json ajax asp.net-mvc


【解决方案1】:

PartialView 不是您所期望的 JSON。将dataType 更改为text/html 或返回JsonResult,即Json( someModel )

【讨论】:

  • 运气不好...试过了,但还是没有结果。
【解决方案2】:

控制器方法

[HttpGet]
public JsonResult EditUser(int dil)
{
   var objUser = objUserLogic.GetUserById(Id);
   var jsonparse= objUser
                 .Select(x => new  //This is trick that prepare json array
                 {
                       name=x.name, 
                       Id=x.Id
                 });
        return Json(jsonparse, JsonRequestBehavior.AllowGet);
}

Ajax 方法

$.ajax({
        url: "/controllerName/getkat",
        type: "GET",
        cache: false,
        contentType: "application/json",
        data: { Id: xxx},
        dataType: "json",
        success: function (data) {
            if (data.length > 0) {
                //Parse Response
                $.each(data, function (i, state) {
                    $('<option>', {
                        value: state.Id
                    }).html(state.name).appendTo($select);
                });
            }
        },
        complete: function () {
        },
        error: function () {
        }
    });

【讨论】:

  • 感谢您的回复,但我的问题是 Json 值没有返回到 AJAX。
  • Json 值不返回 ajax?这意味着您对方法背后的代码的ajax请求并且该方法不是响应值?您可能会逐步调试您拥有的代码。我建议您将 console.log("here") 放在 ajax 方法的成功部分中,也放在发送之前。你可能会发现卡住的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多