Get JSON data from Controller to Dropdown in View

纵然是瞬间 提交于 2019-12-11 17:22:00

问题


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>

回答1:


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>



回答2:


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);
    }
});



回答3:


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>


来源:https://stackoverflow.com/questions/55495005/get-json-data-from-controller-to-dropdown-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!