【问题标题】:Ajax get object from controller to viewAjax 从控制器获取对象以查看
【发布时间】:2014-11-14 11:29:13
【问题描述】:

型号:

        public int Id { get; set; }
        public string Name { get; set; }
        public string Adres { get; set; }
        public string Surname { get; set; }

控制器:

  [HttpGet]
        public Student GetStudentById(int id)
    {
        var output = RepositoryFactory.Create<IStudentRepository>().GetByID(id);
        return output;
    }

JS:

.click(function () {
            $.ajax({
                type: "GET",
                url: '/Admin/GetStudentById/',
                data: { id: object_id }, 
                success: function (response) {
                    $('#toolbox-text').val(response)
                }
                })

问题是我想在 3 个文本框中获取这个 item.Name、item.Adres 和 item.Surname,但是当我输入 response.Adres 时,我什么也得不到。当我输入只是响应时,我得到:文本框中的 MyNewProject.Models.Student。

【问题讨论】:

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


    【解决方案1】:

    尝试从控制器返回 JSON 结果

        public ActionResult GetStudentById(){
               var output = RepositoryFactory.Create<IStudentRepository>().GetByID(id);
               var result = new { Name = output.Name, Adres = output.Adres};
                return Json(result, JsonRequestBehavior.AllowGet);
        }
    

    然后在ajax成功中使用响应:

                success: function (response) {
                    $('#toolbox-text').val(response.Name)
                }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-03
      • 2014-10-07
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 2018-12-11
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多