Select2 Fill Drop down with ajax Web Method not working - c#

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>

Related

.NET Core Ajax still redicted me to json response page

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

Get JSON data from Controller to Dropdown in View

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>

How to get value of checkbox from checkboxlistFor using jquery ajax in MVC

I have a checkboxlistfor control in mvc 5 and want the value of the selected checkbox, once I get the value then send ajax request and fetch the data as per id,
below is the reference link where similar kind of functionality is achieved, in this he has used "for loop" for multiple checkboxes, and I am using checkboxlistfor, using this I am not able to get the value of the selected checkbox.
"https://forums.asp.net/t/2078931.aspx?How+to+get+data+from+checkbox+list+using+jquery+ajax+in+MVC+"
Below is the code I am using to bind checkboxlistfor code
view
#Html.CheckBoxListFor(model => model.sbuIDs,
model => model.Availablesbu,
sb => sb.sbuID,
sb => sb.sbuName,
model => model.Selectedsbu,
htmlListInfo)
controller code
[HttpGet]
public ActionResult AddUsers()
{
var Uvm = new UsersViewModel();
var Selectedsbu = new List<sbu>();
Uvm.Availablesbu = _User.Getallsbu();
Uvm.Selectedsbu = Selectedsbu;
return View(Uvm);
}
public class sbu
{
public int UserID { get; set; }
public int sbuID { get; set; }
public string sbuName { get; set; }
}
public class UsersViewModel()
{
public IEnumerable<sbu> sbu = null;
sbu = new List<sbu>();
public IEnumerable<sbu> Availablesbu { get; set; }
public IEnumerable<sbu> Selectedsbu { get; set; }
public string[] sbuIDs { get; set; }
}
Update
Below is the ajax request i will use:
<script>
$("#CheckBoxListFor").change(function () {
debugger;
var favorite = [];
$.each($("input[name='sbuIDs']:checked"), function () {
favorite.push($(this).val());
});
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: '#Url.Action("Getvalues", "Home")',
data: JSON.stringify({ values: favorite })
});
});
</script>
Controller code
public JsonResult Getvalues(string[] values)
{
//
}
Rendered in HTML a check box list will have a shared name but will have different ids being the name followed by a - and a number identifying the index.
You can use jQuery to get a list of those selected.
$('[name="checkBoxListName"]:checked');
To get an array of their values:
var values = $('[name="checkBoxListName"]:checked').get();
Your sample script should work with some minor changes. 1) use the name selector as your checkboxes will have different ids. 2) Wrap the code in $(document).ready. 3) Just post the raw object and not a string:
<script>
$(document).ready(function() {
$("[name='checkBoxListName']).change(function () {
// code here.
data: { values: favorite }
});
});
</script>
Below is the ajax request i have use
<script>
$("#CheckBoxListFor").change(function () {
debugger;
var favorite = [];
$.each($("input[name='sbuIDs']:checked"), function () {
favorite.push($(this).val());
});
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: '#Url.Action("Getvalues", "Home")',
data: JSON.stringify({ values: favorite })
});
});
</script>
Controller code
public JsonResult Getvalues(string[] values)
{
....
}

Unable to get value from asp.net(Webmethod) and set this value to textbox using jquery [duplicate]

This question already has answers here:
Accessing Asp.net controls using jquery (all options)
(3 answers)
Closed 6 years ago.
I am working with asp.net webmethed i want get a return value and set it to text box
<asp:TextBox ID="TxtSearch" runat="server" placeholder="Search Order" Width="150px"></asp:TextBox>
<input type="submit" name="btn_search" id="btn_search" value="Search">
when i am clicking in submit button it goes to webmethod but i am not unable to get data from it and set it to text box
<asp:TextBox ID="TxtOrder" runat="server" Width="150px"></asp:TextBox>
My Method is given below
[WebMethod]
public static List<Search> Search_Order(string TxtSearch)
{
db_class Connstring = new db_class();
try
{
DataTable dt = new DataTable();
List<Search> SearchItem = new List<Search>();
dt = Connstring.SqlDataTable(#"SELECT OrderNo, Date, CustomerName, ProductID, Price, Total, Quantity, Product_Name FROM Order_Details WHERE OrderNo='" + TxtSearch + "'");
foreach (DataRow dtrow in dt.Rows)
{
Search SearchDeatils = new Search();
SearchDeatils.Product_Name = dtrow["Date"].ToString();
SearchDeatils.ProductID = dtrow["CustomerName"].ToString();
SearchDeatils.Product_Name = dtrow["OrderNo"].ToString();
SearchItem.Add(SearchDeatils);
}
return SearchItem;
}
catch (Exception)
{
throw;
}
}
public class Search //For Order search
{
public string Date { get; set; }
public string CustomerName { get; set; }
public string OrderNo { get; set; }
public string ProductID { get; set; }
public string Price { get; set; }
public string Total { get; set; }
public string Quantity { get; set; }
public string Product_Name { get; set; }
}
And script is
$(window).load(function () {
$("#btn_search").live('click', function () {
$.ajax(
{
type: "POST",
url: "MasterDetails.aspx/Search_Order",
data: "{TxtSearch: '" + $('#TxtSearch').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
alert('Get Data from DB');
$.each(Result.d, function ()
{
document.getElementById('#TxtOrder').value = value.OrderNo;
});
}
});
});
});
Few things to note:
You need to use clientidmode=static in case of HTML server controls and ClientIDMode=Static in case of ASP.NET controls if you are trying to use the IDs on the client side. This is because client ID and server ID are not necessarily the same in ASP.NET
<asp:TextBox ID="TxtOrder" runat="server" Width="150px" ClientIDMode="Static" ></asp:TextBox>
When you are doing the following:
$.each(Result.d, function (){
document.getElementById('#TxtOrder').value = value.OrderNo;
});
You are getting the same input element (the textbox with id=TxtOrder again and again and assigning it different values.
Also, the value.OrderNo is I think undefined inside the function. Instead do something like:
$.each(Result.d, function (key, value){
document.getElementById('#TxtOrder').value = value.OrderNo;
});
As a side note, if you are already using jQuery, the jQuery way to do this would be $("#TxtOrder").val(value.OrderNo);

ASP.NET Web Service JSON Arrays

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.

Categories

Resources