0

I am new to MVC and do not know how to solve this problem.

In a controller I have a list (filled with Api data) serialized to JSON, I need to use this JSON data do populate a dropdown in a View.

I am confused as to what should I return from the controller, what should I be doing next, am I doing this right?

For now I have this:

Model:

public class Tablet {        
    public int Id { get; set; }
    public string ManufactureDate { get; set; }
    public string Description { get; set; }
    public string Country { get; set; }
}

DataController.cs

 Public ActionResult GetData(Tablet tablet)
 {
     List<Tablet> data = new List<Tablet>();

      // ... Code to retrieve the data from API

     string jsonRes = JsonConvert.SerializeObject(data);

     return View(jsonRes);
 }

In the view I need to show the ID in a dropdown:

View.cshtml

<select class="dropdown" id="dropdownData"></select>

<script>
$(document).ready(function () {
    $.ajax({
        url: "/Data/GetData/",
        type: 'GET',
        success: function (jsonRes) {
            console.log(jsonRes[i]);
            var s = '<option value="-1">Please Select</option>';
            for (var i = 0; i < jsonRes.length; i++) {
                s += '<option value="' + jsonRes[i].Id+ '">' + '</option>';
            }
            $("#dropdownData").html(s);
        }
    });
});  
</script>
  • are you populating your `List data` before serializing it? – Cid Apr 03 '19 at 12:22
  • Yes, the list is filled with API data before serialization. It is showing the data as json object in console too. So, the problem for me is passing this json to the View. – wizardress Apr 03 '19 at 12:23
  • Change s += ''; to s += ''; You are only assigning value. But there is no display. Please change this as per the code I have given. Also please make sure you have the values filled in the list. – Jyothish Bhaskaran Apr 03 '19 at 12:24
  • Please review this link : https://stackoverflow.com/questions/30084568/populate-dropdownlist-using-ajax-mvc-4 it is very close to your question. – Mahavir Kumbharvadia Apr 03 '19 at 12:27
  • @JyothishBhaskaran I did that and it returns 'undefined' in the dropdown. – wizardress Apr 03 '19 at 12:27
  • Then it is sure that the issue is with data. @wizardress, could you please provide the json? – Jyothish Bhaskaran Apr 03 '19 at 12:28
  • @JyothishBhaskaran Here you go - https://api.myjson.com/bins/6jd1s . – wizardress Apr 03 '19 at 12:38
  • Have you tried Deserializing it and passing it to the view that way. Then using markup to input it into a dropdown? – JamesS Apr 03 '19 at 13:08
  • Take a look at this post: https://stackoverflow.com/questions/14339089/populating-dropdown-with-json-result-cascading-dropdown-using-mvc3-jquery-aj. Try to return JsonResult instead of ActionResult in your controller. – MarioMendieta Apr 03 '19 at 13:23

3 Answers3

0

Try this, you are setting Value, you are not setting Text for Option Tag, you must be getting blank menu items.Have tested it using your data link and code.

s += '<option value="' + jsonRes[i].Id+ '">'+jsonRes[i].Id + '</option>';

Complete HTML:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<select class="dropdown" id="dropdownData"></select>

<script>
$(document).ready(function () {
    $.ajax({
        url: "https://api.myjson.com/bins/6jd1s",
        type: 'GET',
        success: function (jsonRes) {
            console.log(jsonRes[i]);
            var s = '<option value="-1">Please Select</option>';
            for (var i = 0; i < jsonRes.length; i++) {
                s += '<option value="' + jsonRes[i].Id+ '">'+jsonRes[i].Id + '</option>';
            }
             $("#dropdownData").html(s);
        }
    });
});  
</script>
</body>
</html>
user10954641
  • 73
  • 1
  • 8
0

Try this:

DataController:

[HttpGet]
public JsonResult GetData()
{
    List<Tablet> data = new List<Tablet>();

    // ... Code to retrieve the data from your API

    string jsonRes = JsonConvert.SerializeObject(data);

    return new JsonResult(jsonRes);
}

In your JavaScript:

 $.ajax({
        url: "/Data/GetData/",
        type: "GET",
        dataType: "json",
        cache: false,
        success: function (data) {
            try {
                var parsedData = JSON.parse(data);

                var $select = $('#dropdownData');
                $.each(parsedData, function(i, dataItem) {
                    $('<option>', {
                        value: dataItem.Id
                    }).html(dataItem.Id).appendTo($select);  // or dataItem.Description, or whatever field you want to display to the user
                });
            }
            catch (err) {
                console.log(err);
            }
        }
    },
    error: function (e) {
        console.log(e);
    }
});
MarioMendieta
  • 302
  • 1
  • 10
  • In my controller at 'return new JsonResult(jsonRes)'; it throws the following error "'JsonResult' does not contain a constructor that takes 1 arguments" – wizardress Apr 03 '19 at 14:30
0

Remove the line string jsonRes = JsonConvert.SerializeObject(data);

Also your method GetdData() should return JSON. Check the following code.

public ActionResult GetData(Tablet tablet)
    {
        List<Tablet> data = new List<Tablet>();

        data.Add(new Tablet() { Id = 1, Country = "India", Description = "Test", ManufactureDate = DateTime.UtcNow.ToShortDateString() });
        data.Add(new Tablet() { Id = 1, Country = "Canada", Description = "Test1", ManufactureDate = DateTime.UtcNow.ToShortDateString() });

        //string jsonRes = JsonConvert.SerializeObject(data);

        return Json(data,JsonRequestBehavior.AllowGet);
    }

View Should be like

<select class="dropdown" id="dropdownData"></select>
<script>
$(document).ready(function () {
    $.ajax({
        url: "/Home/GetData/",
        type: 'GET',
        dataType: "json",
        success: function (jsonRes) {
            console.log(jsonRes[i]);
            var s = '<option value="-1">Please Select</option>';
            for (var i = 0; i < jsonRes.length; i++) {
                s += '<option value="' + jsonRes[i].Id + '">' + jsonRes[i].Id+ '</option>';
            }
            $("#dropdownData").html(s);
        }
    });
});
</script>