Georgi
Georgi

Reputation: 297

.get List<string> from controller method and display

I am new to ASP.NET MVC and jQuery and I am trying to pull the following off.

Trying to get this List<string> and display it. And in the GET response I have the following System.Collections.Generic.List1[System.String]` which in this case the 'lable1' also contains.

What am I doing wrong? What should I do?

In the controller:

public List<string> Search(string input, SearchBy searchBy)
{          
        Manager manger = new Manager();
        List<string> MyList = manger.GetData(input, searchBy);                                                         
        return MyList;
}

In the view:

 $('#ii-search').click(function () {
        var number = $('#input').val();
        var typeEn = 'CCC';

        $.ajax({
            url: '@Url.Action("Search", "InitiateInspection")',
            data: { input: number, searchBy: typeEn },
            cache: false,
            success: function (data) {

                for (var i = 0; i < 4; i++) {

                    $('#lable1').html(data[i]);
                }                  
            }
        });

Thanks

Upvotes: 0

Views: 2800

Answers (2)

Renato Vianna
Renato Vianna

Reputation: 158

It is exactly as explained kenttam and in your view do the following:

$('#ii-search').click(function () {
    var number = $('#input').val();
    var typeEn = 'CCC';

    $.ajax({
        url: '@Url.Action("Search", "InitiateInspection")',
        dataType: 'json',
        data: { input: number, searchBy: typeEn },
        cache: false,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {

                $('#lable1').html(data[i]);
            }                  
        }
    });
});

Upvotes: 0

kenttam
kenttam

Reputation: 740

You want to return a JsonResult. So in your controller, try this:

  public JsonResult Search(string input, SearchBy searchBy)
  {          
        Manager manger = new Manager();
        List<string> MyList = manger.GetData(input, searchBy);                                                         
        return Json(MyList, JsonRequestBehavior.AllowGet);
  }

Essentially, the Json function will convert your list into a json object for you.

Upvotes: 3

Related Questions