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>
9
  • are you populating your List<Tablet> data before serializing it? Commented Apr 3, 2019 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. Commented Apr 3, 2019 at 12:23
  • Change s += '<option value="' + jsonRes[i].Id+ '">' + '</option>'; to s += '<option value="' + jsonRes[i].Id+ '">' +jsonRes[i].Id+ '</option>'; 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. Commented Apr 3, 2019 at 12:24
  • Please review this link : stackoverflow.com/questions/30084568/… it is very close to your question. Commented Apr 3, 2019 at 12:27
  • @JyothishBhaskaran I did that and it returns 'undefined' in the dropdown. Commented Apr 3, 2019 at 12:27

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

11 Comments

This works great, thanks! but the problem is I need to take this data from a json in my controller, not from an URL :)
Are you getting data in same format as from your data link? Try logging (in console) data from data link and from controller, are they same?
I am not getting anything from the controller, while the data from the data link is as it should be. I think I am not doing something right in my controller..
return Json(data, JsonRequestBehavior.AllowGet);
try Mario's answer above, instead of using string jsonRes = JsonConvert.SerializeObject(data); you can also use return Json(data, JsonRequestBehavior.AllowGet);
|
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);
    }
});

1 Comment

In my controller at 'return new JsonResult(jsonRes)'; it throws the following error "'JsonResult' does not contain a constructor that takes 1 arguments"
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.