Ajax get object from controller to view

2019-07-22 12:25发布

model :

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

controller:

  [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)
                }
                })

And the problem is that i want to get this item.Name, item.Adres and item.Surname in 3 textboxes but when i type response.Adres i get nothing. When i type just response i get: MyNewProject.Models.Student in textbox.

1条回答
做自己的国王
2楼-- · 2019-07-22 12:59

Try returning a JSON result from the controller

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

Then use the response in the ajax success:

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

Hope it helps!

查看更多
登录 后发表回答