Search code examples
javascriptc#jquery.netpetapoco

JQuery display list of strings .NET MVC


At the bellow code I am trying to fetch a list of strings through JQuery Ajax and .NET framework and display it properly in UI:

JQuery code:

   $.get("/TargetGroups/GetExistingJobTitles")
        .done(function (data) {
            //code to display properties??
        });

C# code:

[HttpGet]
public IEnumerable<string> GetExistingJobTitles()
{
    var foundData = _targetGroupsRepo.GetJobTitles();
    return foundData;
}

While debugging indeed, I get a list of strings. It is out of my knowledge how JQuery can expand the returned list and display it in UI let's say in a ul.

Any help is welcome!


Solution

  • Controller Code

    [HttpGet]
    public JsonResult GetExistingJobTitles()
    {
    var foundData = _targetGroupsRepo.GetJobTitles();
    return Json(foundData,JsonRequestBehavior.AllowGet);
    }
    

    Jquery

    $.get("@Url.Action("GetExistingJobTitles")")
    .done(function (data) {
    var ulJobTitles = $("#ulJobTitles");
    $.each(data, function () {
    ulJobTitles.append($("<li></li>").text(this))
    }
    });
    

    The Jquery code should work with the actual Method, i just like using JSON.

    If u want to pass a object instead of a string

    This is the code for a when foundData is a List of objects

    [HttpGet]
    public JsonResult GetExistingJobTitles()
    {
    var foundData = _targetGroupsRepo.GetJobTitles();
    var returnObj = foundData.Select(x => new
    {
    value = x.Id,
    text = x.Name
    }).ToList();
    return Json(returnObj ,JsonRequestBehavior.AllowGet);
    }
    

    Jquery

    $.get("@Url.Action("GetExistingJobTitles")")
    .done(function (data) {
    var selectJobTitles = $("#ulJobTitles");
    $.each(data, function () {
    selectJobTitles.append($("<option></option>").attr("value", 
    this[value]).text(this[text]))
    }
    });