<asp:Button ID="Button1" runat="server" Text="Submit" />
<script>
$(document).ready(function () {
$("#Button1").click(function () {
var list = [];
var a= $("#TextBox1").val();
var b= $("#TextBox2").val();
var count = a* b;
list.push('test');
for (var i = 1; i <= count; i++) {
var item = $("#DropDownList_" + i + "_").find(":selected").text();
list.splice(i, 0, item);
console.log(list.join());
alert(list[i]);
}
});
});
</script>
Hello guys first time at the stack! I have this jquery code that get all choices of dropdown list and store it in array.
I want pass this array to c# so I can store the values in DB, please help.
You can simply do this using jQuery ajax:-
var dataToSend = { "Data": list};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/SaveData",
data: JSON.stringify(dataToSend),
success: function (msg) {
//success data if any
},
error: function (msg) { //handle error here }
});
Add this method in your page behind (Default.aspx.cs):-
[WebMethod]
public static void SaveData(string[] Data)
{
//Save data to DB
}
Related
I am trying to send stringified array from view with $.ajax but I am constantly getting null in controller.
This is controller function:
[HttpPost]
public void SaveColumnsToDb(string data)
{
var a = data;
}
Console outputs:
str: (2) ['SerialNumber', 'MeasurementUnit']
JSON str: ["SerialNumber","MeasurementUnit"]
Whole function:
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i++) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '#Url.Action("SaveColumnsToDb", "AjaxSelect", new { area = string.Empty })',
type: 'POST',
data: JSON.stringify(columns),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
as a matter of fact, since you are using contentType: 'application/json; charset=utf-8', you are trying to send a json inside of the request body, so use this syntax
[HttpPost]
public void SaveColumnsToDb([FromBody] string[] data)
Changed the parameter name.
When we use an ajax request then we have to pass value in data and In the URL part, we have to give only the action name and controller name.
[HttpPost]
public void SaveColumnsToDb(string dataResponse)
{
var a = dataResponse;
}
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i++) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '#Url.Action("SaveColumnsToDb", "AjaxSelect")',
type: 'POST',
data: { dataResponse: JSON.stringify(columns)},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
I managed to make it work.
Changed data property in $.ajax().
data: JSON.stringify({ data: strColumns })
I am sending only csv string, e.g. "abc;abc;abc"
Controller is same.
On my ASPX page I have the following ComboBox that should be filled from an Ajax WebMethod.
<ajaxToolkit:ComboBox ID ="cbMembers" runat="server"></ajaxToolkit:ComboBox>
The WebMethod that fills the ComboBox is called as follows:
$.ajax({
type: "POST",
url: functions.aspx/members",
data: "{SearchInput: '" + SearchInput + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var cbMembers = $("[id*=cbMembers]");
$.each(r.d, function () {
cbMembers.append( -- My problem is here -- );
})
}
});
WebMethod
List<ListItem> members = new List<ListItem>();
...
if (Reader.HasRows)
{
while (Reader.Read())
{
members.Add(new ListItem
{
Value = HttpUtility.HtmlEncode((string)(Reader["name"])),
Text = HttpUtility.HtmlEncode((string)(Reader["name"]))
});
}
}
return members;
...
The data is retrieved correctly from the WebMethod. I tested it. But my problem is to fill the list items in the ComboBox. Any advice?
success: function (r) {
var cbMembers = $("[id*=cbMembers]");
$.each(r.d, function () {
cbMembers.append( -- How to append the data here? --);
})
}
Try this
$.each(r.d, function () {
cbMembers.append($("<option>",{value:"1",text:"Gloria"}));
})
Try this
$.each(r.d, function () {
cbMembers.append($("<option></option>").val(this['Value']).html(this['Text']));
}
Anyone can tell me how can i use tokenizing in auto-complete for multiple selection, I am make you sure that, i want only with asp.net web from web service
My Code:
$(function () {
// Web servcice javascript code for City
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{ 'username': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
} else {
response([{ label: 'No results found.', val: -1 }]);
}
}
});
},
select: function (e, u) {
if (u.item.val == -1) {
return false;
}
}
});
});
I want to use a web service to fetch data from database and show on front-end for multiple selection
Web Service:
DataTable dt = userRegistrationHelper.GetSkillsList(username);
DataRow[] rows = null;
rows = dt.Select(string.Format("SkillName = {0}", username));
string[] result = new string[rows.Length];
for (int i = 0; i <= rows.Length - 1; i++)
{
result[i] = rows[i]["SkillName"].ToString();
}
return result;
Autocomplete with multiple words or values with comma separated
$(function () {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("[id*=ctl00_ContentMain_TextBoxSkills]").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});
I have this code in my controller:
int number = 0;
public JsonResult JsonData()
{
for (int i = 0; i < 21; i++)
{
number += i;
return Json(number, JsonRequestBehavior.AllowGet);
}
return Json(number, JsonRequestBehavior.AllowGet);
}
And loop with jQuery Ajax script in the view:
<script type="text/javascript">
var tag = true;
$(document).ready(function () {
while (tag) {
$.ajax({
url: "#Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
console.log(data);
$('#counter').html('');
$('#counter').html(data);
if (data == 20) {
tag = false;
}
}
});
}
});
</script>
<div id="counter"></div>
My goal is to make jQuery Ajax to constantly get "number" from action "JasonData" and print that number to "DIV tag" But my current code is not working for some reason, - the result is that browser window will not stop loading if i'm using "while()" loop, if I'm not using "while()" loop it only prints the first value of "number" variable.
Use a setInterval/setTimeout instead of while loop, because continuously running script will block the UI and you can utilize the callback mechanism instead.
$(document).ready(function () {
var interval = window.setInterval(function(){
$.ajax({
url: "#Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
$('#counter').html(data);
if (data == 20) { //<-- make sure data has value 20 and is not an object or anything
window.clearInterval(interval);
}
}
});
}, 1000); //<-- Give interval in milliseconds here
});
Demo
Or with timeout:
$(document).ready(function () {
makeAjaxCall();
});
function makeAjaxCall(){
$.ajax({
url: "#Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
$('#counter').html(data);
if (+data < 20) {
window.setTimeout(makeAjaxCall, 1000); //Duration in ms
}
}
});
}
Demo
I want to call a C# function from aspx code when I type in something in the text box. How can I call a C# function from aspx code on a key down event of a text box.?
Make a Key Down Event
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
Function1();
}
Function
private void Function1()
{
}
Try Jquery ajax -
var ListPostalCode = ["12345"];
var PostalCodeJsonText = JSON.stringify({ list: ListPostalCode });
$.ajax({
type: "POST",
url: "JobManagement.aspx/FindLocation",
data: PostalCodeJsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# WebMethod -
[System.Web.Services.WebMethod()]
public static string FindLocation(List<string> list)
{
try{
string LocationInfo = "";
HttpWebRequest FindLocationreq = (HttpWebRequest)WebRequest.Create("http://ziptasticapi.com/" + list[0]);
FindLocationreq.Method = "GET";
using (WebResponse Statusresponse = FindLocationreq.GetResponse())
{
using (StreamReader rd = new StreamReader(Statusresponse.GetResponseStream()))
{
LocationInfo = rd.ReadToEnd();
}
}
return LocationInfo;
}
catch (Exception ex)
{
return ex.Message;
}
}
Reference 1
Reference 2
Reference 3
Try like this
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
JS:
function EnterEvent(e) {
if (e.keyCode == 13) {//if enter key is pressed condition
__doPostBack('<%=Button1.UniqueId%>', "");
}
}
C#:
protected void Button1_Click(object sender, EventArgs e)
{
}
$("#target").keypress(function() {
var value=$("#target").val();
$.ajax({
type: "POST",
url: "../Webservices/yourwebservice.asmx/webmethodName",
data: "{value: " + value + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result.d);
}
);
});
you can make the call to your webmethod like this on key press.thanks
Here's one way:
ASPX:
<asp:TextBox ID="MyTextBox" ClientIDMode="Static" runat="server" />
JS:
$(function() {
$('#MyTextBox').keyup(function() {
var jsonObj = { c: $(this).val() };
$.ajax({
type: 'POST',
url: 'webservice.aspx/MyCSharpFunction',
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
}
});
});
});
C# (webservice.aspx in this example):
public partial class webservice : System.Web.UI.Page
{
[WebMethod]
public static string MyCSharpFunction(string c)
{
return "You typed " + c;
}
}