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>