Ajax get object from controller to view

安稳与你 提交于 2019-12-13 15:23:49

问题


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:


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!



来源:https://stackoverflow.com/questions/25941205/ajax-get-object-from-controller-to-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!