passing bulk array values to codebehind(cs) using ajax - c#

I have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax
JS
<head runat="server">
<title></title>
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace PassingValueFromJavascriptToCs
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
}
}

First of all the button for aspx is sending your aspx form to a postback so that you would need to change the aspx like this
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
The reason the foo method returns false that you dont want to make your button start a postback. I also added another property UseSubmitBehavior="false" to guarantee it.
The scripts section i changed the values object to a real array and then when sending data , i converted it to json with values object inside. This code will work in your example just fine
Edit : For the working version on my tests
The aspx page (trimmed details to the master page)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
debugger;
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
<asp:Button ID="Button3" UseSubmitBehavior="false" OnClientClick="return test();" runat="server" Text="Deneme" />
</asp:Content>
The RouteConfig and original method
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}

Well at least one issue is your url is "Default.aspx/Done" but the method appears to be on WebForm3.aspx/Done.
What actually happens with your code? Does it error?

Related

can not get data form function using ajax jquery in asp.net c#

i am trying use $.ajax() method in asp.net to fill a html tag but i didn't get any data from on success parameter
i am calling getData function from c# code and I tried to return a string but it doesn't work i also tried to user Response.write() but the same issue
when I alert returned value it show me the aspx page code
as following image
here is my code
Default.apsx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#firstDrop").on("change", function () {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
data: { id: $("#firstDrop").val() },
success: function (data) {
alert(data);
$("#secondDrop").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select runat="server" id="firstDrop">
<option value="0">first select</option><option value="1">second select</option><option value="3">third select</option>
</select>
<select id="secondDrop"></select>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string getData()
{
return"<option>ABC</option><option>CDE</option>";
}
}
Basic rule when creating a webmethod in asp.net.
Your method should be static.
You need to decorate your function with System.Web.Services.WebMethod.
C# Code Behind
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Javascript (Aspx)
Here, in your case make your getdata function static and webmethod as well. When calling the webmethod through ajax use data.d to read the response.
[System.Web.Services.WebMethod]
public static string getData(int id)
{
return "<option>ABC</option><option>CDE</option>";
}
$("#firstDrop").on("change", function() {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
dataType: "json",
data: {
id: $("#firstDrop").val()
},
success: function(data) {
alert(data.d);
$("#secondDrop").html(data.d);
}
});
});
Reference Site:
https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Similar thread "Calling webmethod in webform"
calling-a-webmethod-with-jquery-in-asp-net-webforms

Call asp.net function from javascript function

I want to call asp.net function from a javascript function passing string value.
this is the asp.net function :
[System.Web.Services.WebMethod]
public static string InsertData(string ID)
{
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
using(SqlConnection con = new SqlConnection(source))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con)) {
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
return "True";
}
}
}
So i want to call this function from javascript function which passes the string value "ID" to the the asp.net function.
this is the javascript function i use
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Errorrr');
}
and i call it from here
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
so i have a button and onClick i want to add "Hello" Row to my table but nothing happens and CallError function calls
You can call web method from ajax call in javascript . you need to set url parameter values to function you want to call and you can pass value in the data prameter in json formate.
like this data:"{ParamterName:'VALUE'}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/YouPageMethod",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Method Called Sucess fully');
},
error: function (result) {
alert("error " + result);
}
});
});
</script>
OR
you can call using PageMethod Eample
<script type="text/javascript">
function callInsert() {
PageMethods.InsertDate(id, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
/* call this javascript function */
callInsert();
</script>
You will need to include Jquery first in your page. Then you need to add the following Javascript code.
<script type="text/javascript">
var id ="5"; //your id will be stored here
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/InsertData" + "&?id=" ,
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Success');
},
error: function (xhr, request, status) {
alert(xhr.responseText);
}
});
});
</script>
You need to have scriptManager in your .aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
After that you can call the method using
<script type="text/javascript">
function func(){
PageMethods.InsertData(id,success_msg,failure_msg);
}
</script>

Button Click not triggering jQuery(Ajax) function to update page

I have a website where I display student info. I want to add few text fields on the website and update those fields asynchronously using jQuery(Ajax) on Button click. I believe I have all the requirements in place but the data is still not updated.
Am I missing something here? Clicking buttons does nothing.
Here is my Code -
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Student.Models;
namespace Student.Controllers
{
public class StudentController : Controller
{
public ActionResult Index()
{
return View("Student");
}
[HttpPost()]
public ActionResult DisplayStudentName(string id)
{
StudentDataContext db = new StudentDataContext();
var StudentName = (from p in db.vwStudent.Where(a => a.StudentId == id)
group p by p.StudentName into g
select g.Key).FirstOrDefault();
ViewData["StudentName"] = StudentName;
return View("Student");
}
[HttpPost()]
public ActionResult DisplayStudentStatus(int? id, string flg)
{
AccountDataContext db = new AccountDataContext();
var StudentStatus = (from p in db.vwStudent.Where(a => a.StudentId == id && a.LastFlag == flg)
group p by p.Status into g
select g.Key).FirstOrDefault();
ViewData["StudentStatus "] = StudentStatus;
return View("Student");
}
}
}
jQuery:
$("#Button1").click(function() {
var link = '<%= Url.Action("DisplayStudentName", "Student")';
$.ajax({
url: link,
data: "{id: '<%= ViewContext.RouteData.Values["id"] %>'}",
dataType: "html",
success: Success,
error: Fail
});
});
$("#Button2").click(function() {
var link = '<%= Url.Action("DisplayStudentStatus", "Student")';
$.ajax({
url: link,
data: "{id: '<%= ViewContext.RouteData.Values["id"] %>' ,
flg: '<%= ViewContext.RouteData.Values["flg"] %>'}",
dataType: "html",
success: Success,
error: Fail
});
});
function Success(){
alert("Success");
}
function Fail(){
alert("Fail");
}
View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Student Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" method="get" runat="server">
Student ID:<input type="text" name="id" id="StudentId" value="<%=HttpContext.Current.Request.QueryString["id"]%>" /><br />
Student Name:<input type="text" name="StudentName" id="StudentName" value="<%=ViewData["StudentName"]%>"/>
<div id="Btn1"><input type="button" value="Display Student Name" name="Btn1" id="Button1" />
</div>
Student Status:<input type="text" name="StudentStatus" id="StudentStatus" value="<%=HttpContext.Current.Request.QueryString["StudentStatus"]%>" />
<div id="Btn2"><input type="button" value="Display Profit Center" name="Btn2" id="Button2" />
</div>
</div>
</form>
</asp:Content>
Thanks in advance
There are a couple of issues with your code that I see:
You should not wrap the data parameters into single quotes.
Your success and error parameters should not be strings. They should be functions
You should never hardcode urls in an ASP.NET MVC application. You should always use url helpers when dealing with urls
So:
$("#Button1").click(function() {
var link = '<%= Url.Action("DisplayStudentName", "Student")';
$.ajax({
url: link,
data: { id: '<%= ViewContext.RouteData.Values["id"] %>' },
success: Success,
error: Fail
});
});
$("#Button2").click(function() {
var link = '<%= Url.Action("DisplayStudentStatus", "Student")';
$.ajax({
url: link,
data: {
id: '<%= ViewContext.RouteData.Values["id"] %>' ,
flg: '<%= ViewContext.RouteData.Values["flg"] %>'
},
success: Success,
error: Fail
});
});
where obviously you must have declared the 2 functions used:
function Success(data) {
// ...
}
function Fail() {
// ...
}
need to mention post in ur ajax parameters
$.ajax({
url: link,
type: 'post',
Also you have mentioned json as the datatype in your ajax function but your action is returning text/html.
Make these 2 changes and if it doesnt work then check fiddler to see what response you are getting from the server.
If you are getting a valid response then check your success function to see if you are doin things right.
If you want to support get and post scenarios on your action then change the attribute on your action to
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]

WebMethod Error

I am getting "NetworkError: 500 Internal Server Error - http://localhost:5963/default.aspx/Call" when am calling this server side function using jquery
<html>
<head>
<script src="scripts/jquery-1.2.6-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
type: "POST",`enter code here`
url: "default.aspx/Call",
data: "{}",
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
success: function (msg) {
alert("sdsd");
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:RadioButton runat="server" ID="btn" Text="A" />
</form>
</body>
</html>
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static void Call(string value)
{
var x = value;
}
First of all this script won't return anything because you're using the wrong id of a server control. When a server control is rendered, it's id changes.
Try using :
$("#<%=btn.ClientID %>")
You have another problem. You're calling an overloaded web method, so you need to pass some data :
data: "{'value': 'somevalue'}",
Hope this will help.
Does this path scripts/jquery-1.2.6-vsdoc.js give you proper jQuery file? It looks like you're trying to load vsdoc file as a normal library.
The first thing you need to do is use the FireBug console. That will tell you what the error is.
But your code won't work because your return type is void. You actually need to return something back to the client. Change it to this:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string Call(string value)
{
var x = value;
return x; // Silly example
}

Autocomplete JQuery is not working

Merged with jQueryUI Autocomplete Plugin not working.
I am NEW in JQ stuff. So basically I have a simple textbox in which I want user to search some items. I am using JQ for this. I read this link which implements this example:
http://aspnetnova.blogspot.com/2009/06/simple-jquery-ajax-server-side.html
Here is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<style type="text/css">
.login
{}
</style>
<script type ="text/javascript">
var data = "";
$(document).ready(function () {
$("#tbSearch").click(function () {
$.ajax({
type: "POST",
url: "AgentList.aspx/LoadData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
data = msg.d.split(" ");
$('#<%= tbSearch.ClientID %>').autocomplete(data);
}
});
});
});
</script>
</asp:Content>
<asp:TextBox ID="tbSearch" runat="server" ontextchanged="tbSearch_TextChanged"></asp:TextBox>
Here is my code behind:
#region "Auto Complete"
[System.Web.Services.WebMethod]
public static string LoadData()
{
return "S M SMI SM A ABC ABCD ABCI";
}
#endregion
What I am doing wrong here?

Categories

Resources