How to get data from a gidview to jquery - c#

I am having gridview showing data from database such as
ProductID ProductName Price
----------------------------------
A00001 Apple 10.00 ADDTOCART
The ADDTOCART is a button.
GridViewRow gr = ((sender as LinkButton).NamingContainer as GridViewRow);
string itemId = gr.Cells[0].Text.Trim();
These are the code I use for codebehind to get the ProductID when click on ADDTOCART
Need assist for the code which can let the variable I declared in Jquery to get the ProductID like what the codebehind do when I click the ADDTOCART button.
function ShowCurrentTime() {
var name = "The name";//$("#<%=txtUserName.ClientID%>")[0].value; //get the data.
var id = "The id";//$("#<%=TextBox1.ClientID%>")[0].value; //get the data.
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}
function OnSuccess(response) { //fetching object come out, object inside got name and id, need to specific which data you want by obj.id/obj.name
var obj = response.d; //fetching the webmethod
alert(obj.id + "" + obj.name) //display the return
$('#trycart').append("<li>" + obj.id + "</li>");
$('#cart').append("<tr><td>" + obj.id + "</td><td>" + obj.name +"</td></tr>"); //access the table id=cart, add in the data comeback from webmethod.
}
I need assist to have the var name to have the product name, and var id to have the id when I click ADDTOCART.

The element name and selectors can be manipulated by looking at the Dom.
In the button onclick pass this as parameter
function ShowCurrentTime(element)
{
var name = $(element).closest("tr").find("input[id*='txtUserName']").val();
var id = $(element).closest("tr").find("input[id*='TextBox1']").val();
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}

I guess that Your data from database is in your C# application, which is on your server side. The code above are jquery/javascript, which is on your client side.
It's very important to know the difference on server side and client side. Basically say, everything you can see from "view source" from browser, are client side, otherwise, on server side.
So go back to your question, you can build html with data from database in your c# application, or build json data object, and in turn use it in jquery.
Hope helps

Related

Ajax success is not called after JsonResult

I am trying to add the record to DB using Ajax and get the data back from JsonResult if success, in order to call the function further, but somehow always land in the error: parseerror. However, the record is inserted in DB.
Here is my post method:
$("body").on("click", "#btnAdd", function () {
var txtTermName = $("#txtTermsName");
var txtAlternativeTerms = $("#txtAlternativeTerms");
$.ajax({
type: "POST",
url: "/Administration/AddTerm",
data: '{name: "' + txtTermName.val() + '", alternatives: "' + txtAlternativeTerms.val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var row = $("#tblTerms tr:last-child");
if ($("#tblTerms tr:last-child span").eq(0).html() != " ") {
row = row.clone();
}
AppendRow(row, r.Name, r.Alternatives);
txtTermName.val("");
txtAlternativeTerms.val("");
},
error: function(textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
});
And my controller JsonResult:
[HttpPost]
public JsonResult AddTerm(Term term)
{
this.SaveTerm(term);
return Json(term);
}
Any comment or suggestion is appreciated
UPDATE
Json(term).Data contents:
- Json(term).Data {Models.Term} object {Models.Term}
+ ChangedBy
Description null string
ID 27 int
Inactive false bool
Name "sdfgdsgf" string
SynonymsList "sdfgdsgfdsgsdgf" string
+ Updated {09.08.2018 10:00:50} System.DateTime
Looks like an exception is being called somewhere after your database save call (I take it the SaveTerm method does more than just save the item?) resulting in an error page being returned instead of JSON - hence the parse error.
Try adding a Try { } Catch { } to the action and I reckon there will be an exception caught from the SaveTerm method.

webmethod isn't catching ajax POST

I'm trying to call a server side method with ajax. This is what I've got:
Client side:
function accept(thisButton) {
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: '{param: "' + $(thisButton).prev().val() + '" }',
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}
Server side:
[System.Web.Services.WebMethod]
public static string editMaxUsers(string maxUsers)
{
return maxUsers; //I also have a breakpoint here that isn't stopping the execute
}
When I check the calls with firebug I can see that the POST is being sent and looks fine. But Nothing seems to be happening on server side. What am I doing wrong?
EDIT: Don't know if it's relevant, but the url already contains some parameters. I've tried the following url: "Default.aspx/" + window.location.search + "editMaxUsers" but no success.
The parameters of your WebMethod need to match the parameter name you are passing in.
Change
data: '{param: "' + $(thisButton).prev().val() + '" }',
to
data: '{maxUsers: "' + $(thisButton).prev().val() + '" }',
1.Go to App_Start/RouteConfig and change
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
2.As #F11 said the paramter in the WebMethod and the key in the json object should be with the same name and what I strongly recommend is not to build json object manually. It is better to do:
function accept(thisButton) {
var data = {};
data.maxUsers = $(thisButton).prev().val();
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: JSON.stringify(data),
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}

JQuery AJAX method executes both "success" and "failure"

I have an AJAX method to tell the user whether or not an email is available when registering.
$('#mainArea_txtEmail').keyup(function (e) {
var inputemail = $(this).val();
if (inputemail.length > 5)
{
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert("available"),
failure: alert("unavailable")
});
}
});
When a user types in an email, whether it is available or not, the browser displays the success alert and then the failure alert every time.
Here is the C# method:
[System.Web.Services.WebMethod]
public static string isEmailAvailable(string email)
{
BasePage page = new BasePage();
string returnvalue;
if (page.db.UserGet(email) == null)
{
returnvalue = "true";
}
else
{
returnvalue = "false";
}
return returnvalue;
}
The db.UserGet method will try and find a database record of a user with the email address matching the email parameter. If there is one, then a User class instance is populated and page.db.UserGet is not null, meaning the email is taken. If it is still null, then no user with that email was found and the email is available.
What am I doing wrong here?
I was following this tutorial (http://www.c-sharpcorner.com/UploadFile/20abe2/how-to-check-user-name-or-email-availability-using-Asp-Net)
Your syntax won't work, you can't use alert as the callback function. alert needs to be wrapped in a proper function or it will fire immediately
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(serverResponse) {
alert("available");
/* do something with serverResponse */
},
failure: function() { alert("available"); }
});
$.ajax API Reference

How to call webmethod in Asp.net C#

I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

Redirect after an ajax request in a click event

I'm using JScript + ASP.NET. I got a form with 2 inputs (user and password) and a button. What I'm trying to do is to:
1- Fire a click event
2- Look inside a database if the user exist
3- Give back the answer
4- If the answer is true, POST some data to an other page AND redirect to it.
I first tried to do this with ASP.NET. To POST data with ASP.NET I need to use PostBackUrl property, but the problem is that PostBackUrl ignore my click event.
I then tried to do this with jscript. On my click event (jquery), I use $.ajax to POST data to access my database, give the answer back in json...and I'm stuck there. In both method, I'm stuck at point 4.
ASP.NET
protected void SignIn_OnClick(object sender, EventArgs e)
{
Clients client = (Clients)clientDAO.getUsername(text1.Text, password2.Text);
if (client != null)
{
Session.Add("SessionNoClient", "1272");
Session.Add("CurrentQuote", "-1");
Session.Add("UnitSystem", "0");
Session.Add("SessionAdministrator", "0");
//How to redirect with POST here
}
}
JScript:
$("#m_bLogin").click(function () {
var username = $("#text1").val();
var password = $("#password2").val();
var form = $("#formClient");
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
});
});
You could do something like that:
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
}).done(function() {
window.location.href = "YourNewPage.aspx";
});

Categories

Resources