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>
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>
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);
}
});
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>
Related
I try to insert data to database with .NET Core Framework with AJAX hope this can return json response when it success, it success but i don't know it throws me to page fill it the response of json, not still in page when i insert the data. (sorry for link image, i'm not yet proper to upload image, stackoverflow say)
This is output i get;
https://i.stack.imgur.com/x7UY4.png
This is create in contoller;
https://i.stack.imgur.com/0StbY.png
This is my javascript code;
var isDuplicate = true;
$("#formProduct").validate({
rules: {
NameProduct: {
required: true,
minlength: 5
}
},
messages: {
NameProduct: {
required: "Data tidak boleh kosong",
minlength: "Minimal 5 huruf"
}
},
submitHandler:function(form){
debugger;
if (isDuplicate) {
return false;
} else {
submitAJAX(form);
}
debugger;
}
});
function submitAJAX(form) {
var fromData = new FormData();
var dataForm = $(form).serializeArray();
$.each(dataForm, function (key, input) {
fromData.append(input.name, input.value);
});
var file = $("#ImageFile").prop("files");
if (file.length > 0) {
fromData.append("ImageFile", file[0]);
}
$.ajax({
url: "/Product/Create",
data: fromData,
method: "post",
dataType: "json",
success: function (response) {
var data = response;
if (data.success) {
$("#modal_sm").modal("hide");
toastr.success("Data success input");
window.location.reload();
}
else {
$("#modal_sm").modal("hide");
toastr.error("Data failed input");
}
}
});
}
I hope can run ajax without get throw to page json result
I guess you used <input type="submit"/> or <button></button> which will automatically submit the form when it is clicked.
Here is a whole working demo:
Model
public class VMProduct
{
public string Name { get; set; }
public int Age { get; set; }
public IFormFile ImageFile { get; set; }
}
public class VMResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
View
#model VMProduct
<form>
<input type="file" asp-for="ImageFile" />
<input asp-for="Age" />
<input asp-for="Name" />
<input type="submit" value="Post"/>
</form>
#section Scripts
{
<script>
$('form').on('submit', function(e) {
var submittedform = $(this);
e.preventDefault(); //be sure add this if you use submit button
submitAJAX(submittedform);
});
function submitAJAX(form) {
var fromData = new FormData();
var dataForm = $(form).serializeArray();
$.each(dataForm, function (key, input) {
fromData.append(input.name, input.value);
});
var file = $("#ImageFile").prop("files");
if (file.length > 0) {
fromData.append("ImageFile", file[0]);
}
$.ajax({
url: "/Product/Create",
data: fromData,
method: "post",
contentType: false, //be sure add this...
processData: false, //be sure add this...
dataType: "json",
success: function (response) {
var data = response;
if (data.success) {
//do your stuff...
}
else {
//do your stuff...
}
}
});
}
</script>
}
CSS
User select2 version Select2-4.0.13
and bootstrap4
<link href="Styles/Select2-4.0.13/select2.min.css" rel="stylesheet" type="text/css" />
<link href="Styles/Select2-4.0.13/select2-bootstrap4.min.css" rel="stylesheet" type="text/css" />
ASPX
Created Dropdown list Name with class js-data-example-ajax
<form id="form1" runat="server">
<asp:DropDownList runat="server" class="js-data-example-ajax" style="width: 300px">
</asp:DropDownList>
</form>
JAVA SCRIPT
loaded data to select2 dropdown using ajax web method call in document ready method
but its raising error and not working properly
<script src="Scripts/jquery-3.4.1/jquery-3.4.1.min.css" type="text/javascript"></script>
<script src="Scripts/Select2-4.0.13/select2.full.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.js-data-example-ajax').select2({
theme: 'bootstrap4',
minimumInputLength: 1,
containerCssClass: ':all:',
allowClear: true,
ajax: {
url: 'WebForm1.aspx/getsource',
dataType: 'json',
//type: "POST",
params: {
contentType: 'application/json; charset=utf-8'
},
data: function (params) {
var query = {
q: params.term,
page: params.page
}
return query;
},
processResults: function (data, params) {
params.page = params.page || 1;
data = jQuery.map(data.results, function (obj) {
obj.id = obj.id;
obj.text = obj.text;
return obj;
});
return {
results: data,
pagination: {
more: params.page * 30 < 4//total records
}
};
},
success: function (data) {
console.log("SUCCESS: ", data);
},
error: function (data) {
console.log("ERROR: ", data);
},
cache: true
}
});
});
</script>
.CS File
Created Method as web method to load data to dropdown list with select2
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getsource(string q, int page)
{
Select2ModelMain obj = new Select2ModelMain();
obj.results = new List<SelectResult>();
SelectResult objdata1 = new SelectResult();
objdata1.id = 1;
objdata1.text = "INDIA";
obj.results.Add(objdata1);
objdata1 = new SelectResult();
objdata1.id = 2;
objdata1.text = "AMERICA";
obj.results.Add(objdata1);
objdata1 = new SelectResult();
objdata1.id = 3;
objdata1.text = "CHINA";
obj.results.Add(objdata1);
objdata1 = new SelectResult();
objdata1.id = 4;
objdata1.text = "SRILANKA";
obj.results.Add(objdata1);
obj.pagination = new SelectPage();
obj.pagination.more = "true";
if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
{
obj.results = obj.results.Where(x => x.text.ToLower().StartsWith(q.ToLower())).ToList();
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string test = serializer.Serialize(obj);
return test;
}
public class Select2ModelMain
{
public List<SelectResult> results { get; set; }
public SelectPage pagination { get; set; }
}
public class SelectResult
{
public int id { get; set; }
public string text { get; set; }
public string disabled { get; set; }
}
public class SelectPage
{
public string more { get; set; }
}
output
Step 1:
On Select2ModelMain change
public List<SelectResult> results { get; set; }
to (I'm having an issue on if it is name results)
public List<SelectResult> items { get; set; }
Step 2:
Try this javascript as an initial to check if it's working.
Note: Make sure that the action method is 'POST' instead of 'GET' i'm not sure what is the issue on if GET for select2 for a normal ajax call it works.
Side Note:
When using GET on normal ajax request this should be set to UseHttpGet = true
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
For other options when using select2 remote query
$(document).ready(function () {
$('.js-data-example-ajax').select2({
ajax: {
url: 'TestSelect2Page.aspx/getsource',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
delay: 250,
data: function (params) {
var search = '';
if (params.term !== undefined) {
search = params.term;
}
return "{'q': '" + search + "'}";
},
processResults: function (data) {
var items = JSON.parse(data.d).items
if (items == null) {
return null;
}
return {
results: items
};
}
},
placeholder: 'Search here',
minimumInputLength: 1
});
});
OUTPUT 1:
OUTPUT 2:
I hope this helps. Happy coding.
Thank you so much its working...
enter image description here
but we are facing another issue
i.e. selected event changed OnSelectedIndexChanged is not working
so we added another line "<asp:ListItem Selected="True"></asp:ListItem>"
after this it fires OnSelectedIndexChanged but its not showing selected Item
2
3
<asp:Label ID="LblItemName" runat="server" Style="font-weight: bold;" Text="Product Name"></asp:Label>
<asp:DropDownList runat="server" ID="txtItemName" data-width="100%" CssClass="select2-single input-sm w-100"
AutoPostBack="true" OnSelectedIndexChanged="txtItemName_SelectedIndexChanged">
<asp:ListItem Selected="True"></asp:ListItem>
</asp:DropDownList>
I only get the text message Selektoni Tipin, but I dont get any values from the tables I only get undefined
AJAX script
script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Dokument/Dokument",
data: "{}",
success: function (data) {
var s = '<option value="-1">Selektoni Tipin</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].Id_Tipi + '">' + data[i].Emri_llojit + '</option>';
}
$("#tipiDropdown").html(s);
}
});
});
</script>
Controller method
public ActionResult Dokument()
{
return View();
}
// GET: NgarkoDokument
public ActionResult GetTipi(int tipiId)
{
Test_kristiEntities db = new Test_kristiEntities();
return Json(db.Tipi.Select(x => new
{
Id_Tipi = x.Id_Tipi,
Emri_llojit = x.Emri_llojit
}).ToList(), JsonRequestBehavior.AllowGet);
// return View();
}
Model i built with some tables
public class NgarkoDokument
{
public Dokumenti Dokumenti { get; set; }
public Fusha_Indeksimit FushaIndeksimit { get; set; }
public Vendndodhja_Fizike Vendndodhja_fizike { get; set; }
public Tipi Tipi { get; set; }
}
And here is the html
<select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>
I have a problem when I try to use the plugin Jquery Autocomplete. I am use ASP.Net C# and SQL for the BD.
The error is the follow:
SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
I read into forums and say that it's for an invalid JSON format but I don't know how fix it or if it is the error.
My Model:
public class ListasAutocompletarModel
{
public int value { get; set; }
public string label { get; set; }
}
My Controller:
public JsonResult mostrarListaDatosMaestrosCodigo(string Codigo)
{
List<ListasAutocompletarModel> list = new List<ListasAutocompletarModel>();
try
{
DataTable datos = DM.mostrar_Lista_Codigo(Codigo);
foreach (DataRow data in datos.Rows)
{
list.Add(new ListasAutocompletarModel
{
value = Convert.ToInt32(data["ID"]),
label = data["Codigo"].ToString(),
});
}
}
catch (Exception e)
{
Classes.ErrorLogger.Registrar(this, e.ToString());
}
return Json(list,JsonRequestBehavior.AllowGet);
}
And my js:
$('#txtDatosMaestros_Codigo').autocomplete({
source: function (request, response) {
$.ajax({
url: "/DatosMaestros/mostrarListaDatosMaestrosCodigo",
type: "POST",
dataType: "json",
data: { Codigo: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.value };
}))
}
});
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
Please help me.
I need some help with my web service and json call.. stuck trying to get the data returned, I've done this successful with strings and objects.. but not an array...
My Web Service Contains:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetSearchCriteria()
{
var js = new JavaScriptSerializer();
var obj = HttpContext.Current.Session["mysessionname"];
if (obj == null)
{
var result = new Criteria[]
{
new Criteria() { Key = Guid.NewGuid(), Operator = "=", ColumnName = "CheckID", Value = "" }
};
var serial = js.Serialize(result);
return serial;
}
else
{
var serial = js.Serialize((Criteria[])obj);
return serial;
}
}
Criteria is:
[Serializable]
public class Criteria
{
public Guid Key { get; set; }
public string ColumnName { get; set; }
public string Operator { get; set; }
public string Value { get; set; }
}
My Page Contains:
<script type="text/javascript">
function RefreshCriteria() {
$.ajax({
type: 'POST',
url: '<%= System.Web.VirtualPathUtility.ToAbsolute("~/Services/WebService.asmx/GetSearchCriteria") %>',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
success: function (data) {
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
}
});
}
$(document).ready(function () {
RefreshCriteria();
});
</script>
What I'm getting is undefined every time.. tried doing
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
$(data).each(function (i, obj) {
alert(obj);
});
$(data).each(function (i) {
alert(this);
});
None worked so far..
you can tighten up the ajax
$.ajax({
type: 'POST',
url: '*you need a url here*',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
console.log(item);
});
}
});
next using either firebug or fiddler monitor the request/response to ensure what you are sending and receiving is what you expected.