Подтвердить что ты не робот

Как получить список из контроллера mvc для просмотра с помощью jquery ajax

Мне нужно получить список из mvc-контроллера для просмотра с помощью jquery ajax. Как мне это сделать. это мой код. Сообщение об ошибке предупреждения.

В контроллере

 public class FoodController : Controller
    {
       [System.Web.Mvc.HttpPost]
        public IList<Food> getFoodDetails(int userId)
        {
            IList<Food> FoodList = new List<Food>();

                FoodList = FoodService.getFoodDetails(userId);

                return (FoodList);
        }
    }

В поле зрения

function GetFoodDetails() {
        debugger;
        $.ajax({
            type: "POST",
            url: "Food/getFoodDetails",
            data: '{userId:"' + Id + '"}',
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (result) {
                debugger;
                alert(result)
            },
            error: function (response) {
                debugger;
                alert('eror');
            }
        });

    }

enter image description here

4b9b3361

Ответ 1

Почему вы используете HttpPost для GET-метода? И нужно вернуть JsonResult.

public class FoodController : Controller
{

    public JsonResult getFoodDetails(int userId)
    {
        IList<Food> FoodList = new List<Food>();

        FoodList = FoodService.getFoodDetails(userId);

        return Json (new{ FoodList = FoodList }, JsonRequestBehavior.AllowGet);
    }
}


function GetFoodDetails() {
    debugger;
    $.ajax({
        type: "GET",
        url: "Food/getFoodDetails",
        data: { userId: Id },
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            debugger;
            alert(result)
        },
        error: function (response) {
            debugger;
            alert('eror');
        }
    });

}

Ответ 2

Вы можете сделать это, вернуть данные JSON и распечатать его

Прочитайте полный учебник: http://www.c-sharpcorner.com/UploadFile/3d39b4/rendering-a-partial-view-and-json-data-using-ajax-in-Asp-Net/

public JsonResult BooksByPublisherId(int id)
{
      IEnumerable<BookModel> modelList = new List<BookModel>();
      using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
      {
            var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();
            modelList = books.Select(x =>
                        new BookModel()
                        {
                                   Title = x.Title,
                                   Author = x.Auther,
                                   Year = x.Year,
                                    Price = x.Price
                          });
            }
    return Json(modelList,JsonRequestBehavior.AllowGet);

        }

Javascript

$.ajax({

                cache: false,

                type: "GET",

                url: "@(Url.RouteUrl("BooksByPublisherId"))",

                data: { "id": id },

                success: function (data) {

                    var result = "";

                    booksDiv.html('');

                    $.each(data, function (id, book) {

                        result += '<b>Title : </b>' + book.Title + '<br/>' +

                                    '<b> Author :</b>' + book.Author + '<br/>' +

                                     '<b> Year :</b>' + book.Year + '<br/>' +

                                      '<b> Price :</b>' + book.Price + '<hr/>';

                    });

                    booksDiv.html(result);

                },

                error: function (xhr, ajaxOptions, thrownError) {

                    alert('Failed to retrieve books.');

                }

            });

Ответ 3

Причина, по которой я не получаю результат, была. Я забыл добавить json2.js в библиотеку

 public class FoodController : Controller
    {
       [System.Web.Mvc.HttpGet]
        public JsonResult getFoodDetails(int userId)
        {
            IList<Food> FoodList = new List<Food>();

            FoodList = FoodService.getFoodDetails(userId);

            return Json (FoodList, JsonRequestBehavior.AllowGet);
        }
    }

function GetFoodDetails() {
    debugger;
    $.ajax({
        type: "GET",
        url: "Food/getFoodDetails",
        data: { userId: Id },
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            debugger;
            alert(result)
        },
        error: function (response) {
            debugger;
            alert('eror');
        }
    });

}

Ответ 4

Попробуйте следующее:

Вид:

    [System.Web.Mvc.HttpGet]
    public JsonResult getFoodDetails(int? userId)
    {
        IList<Food> FoodList = new List<Food>();

        FoodList = FoodService.getFoodDetails(userId);

        return Json (new { Flist = FoodList } , JsonRequestBehavior.AllowGet);
    }

Контроллер:

function GetFoodDetails() {
    debugger;
    $.ajax({
        type: "GET",       // make it get request instead //
        url: "Food/getFoodDetails",
        data: { userId: Id },      
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            debugger;
            alert(result)
        },
        error: function (response) {
            debugger;
            alert('error');
        }
    });

}

Или, если запрос ajax создает проблемы, вы можете использовать $.getJSON как:

$.getJSON("Food/getFoodDetails", { userId: Id } , function( data ) {....});

Ответ 5

   $(document).ready(function () {
        var data = new Array();
        $.ajax({
            url: "list",
            type: "Get",
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index) {
                    // alert("id= "+data[index].id+" name="+data[index].name);
                    $('#myTable tbody').append("<tr class='child'><td>" + data[index].id + "</td><td>" + data[index].name + "</td></tr>");
                });

            },
            error: function (msg) { alert(msg); }
        });
    });


    @Controller
    public class StudentController
    {

        @Autowired
        StudentService studentService;
        @RequestMapping(value= "/list", method= RequestMethod.GET)

        @ResponseBody
        public List<Student> dispalyPage()
        {

            return studentService.getAllStudentList();
        }
    }

Ответ 6

1 - создать одну модель для имени User

public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Family { get; set; }
    }

2 - Создайте один ActionResult для NameOf GetUsers

public ActionResult GetUsers()
        {
            List<User> users = new List<Models.User>()
            {
                new Models.User(){Id=1,Name="Diako",Family="Hasani"},
                new Models.User(){Id=2,Name="Sina",Family="Moradi"},
                new Models.User(){Id=3,Name="Hamid",Family="Chopani"}
            };

            return Json(users,JsonRequestBehavior.AllowGet);
        }

3-Для вашего просмотра Создать один div

<div id="parent"></div>

4-напишите этот код в script

<script>
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "/Home/GetUsers",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {

                    for (var i in result) {
                        $('#parent').append('<p>' + result[i].Name + '</p>');
                    }

                },
                error: function (response) {
                    alert('eror');
                }
            });
        });


    </script>