Ajax从控制器获取对象以进行查看

时间:2014-09-19 19:35:50

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

模特:

        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。

1 个答案:

答案 0 :(得分:2)

尝试从控制器返回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)
            }

希望它有所帮助!