html table jQuery json value pass - c#

I want to pass value through jQuery Json.The problem is that while passing the value then,it have some problem,thats why it is not calling c# code.
This is the html table:
$(function ()
{
debugger
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm7.aspx/BindCategoryDatatable",
data: "{}",
dataType: "json",
success: function (dt) {
debugger;
for (var i = 0; i < dt.d.length; i++) {
$("#tblid > tbody").append("<tr><td> <input type='checkbox' class='chk' id=" + dt.d[i].projectid + " /></td><td>" + dt.d[i].projectname + "</td><td>" + dt.d[i].Name + "</td><td>" + dt.d[i].technology + "</td><td>" + dt.d[i].projectliveurl + "</td><td><input type='image' src=" + dt.d[i].StatusImage + " onclick='actvstatus(" + dt.d[i].projectid + ", " + dt.d[i].status + ")' alt='Submit' width='18' height='18'> </td><td>" + dt.d[i].DisplayOrder + "</td><td> <i class='ui-tooltip fa fa-pencil' onclick='btnQueryString_Click(" + dt.d[i].projectid + ")' style='font-size:22px;margin-left: 32px;'></i><i class='ui-tooltip fa fa-trash-o' onclick='deleteRecord(" + dt.d[i].projectid + ")' style='font-size: 22px;margin-left: 32px;color:red'></i> </tr>");
}
$("#tblid").DataTable();
},
error: function (result) {
alert("Error");
}
});
});
This is my c# Code:
[WebMethod]
public static List<mProjects> BindCategoryDatatable(int catid)
{
clsProjectBL objcategory = new clsProjectBL();
List<mProjects> modelCategory = new List<mProjects>();
DataTable dtCategory = new DataTable();
//dtCategory = objcategory.GetAllCategoryDetails("admin");
dtCategory = objcategory.GetAllProjectDetails("admin", catid);
if (dtCategory.Rows.Count > 0)
{
modelCategory = (from DataRow dr in dtCategory.Rows
select new mProjects()
{
projectid = Convert.ToInt32(dr["projectid"]),
CategoryID = Convert.ToInt32(dr["CategoryID"]),
projectname = dr["projectname"].ToString(),
Name = dr["Name"].ToString(),
technology = dr["technology"].ToString(),
projectliveurl = dr["projectliveurl"].ToString(),
DisplayOrder = Convert.ToInt32(dr["DisplayOrder"]),
status = Convert.ToBoolean(dr["status"]),
StatusImage = dr["StatusImage"].ToString(),
//Deleted = Convert.ToBoolean(dr["Deleted"])
}).ToList();
}
return modelCategory;
}
The value is not pass through webmethod...

Your back-end required a parameter catid so you have to pass catid to AJAX call as #BenG and #palash answer with data attribute.
data: { catid: 1 }
Or you pass it to the url with format
url: "WebForm7.aspx/BindCategoryDatatable?catid=" + YOUR_ID.
Otherwise, it will not be worked because BindCategoryDatatable return an empty list.

Related

Get next 8 rows from database on button click using linq to sql and web method

I am creating a webpage in which I fetch top 8 rows from database on page load. I put load more button on my bottom of my web page. What I want is when I click on load more button it shows me next new 8 rows and skip previous records and if there is no new record found then show me nothing.
Below is my code which I was trying but it was repeating same duplicate records.
//Below event is fetching top 8 rows on page load
function viewAllEvents() {
$.ajax({
url: "Event.aspx/viewEvents",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
//Below event is for when load more button is clicked
function addTabs() {
$.ajax({
url: "Event.aspx/addTab",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
Below is my web methods:
[WebMethod]
public static List<EVENT> viewEvents()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Take(8).ToList();
return slist;
}
[WebMethod]
public static List<EVENT> addTab()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Skip(8).Distinct().ToList();
return slist;
}
Though I didn't use your code but I believe if you can go through this example below then you'll know what to do:
First declare a global variable which will count the record returned so far:
private int recordCount = 0;
Then in the click event do the following:
//My sample data
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8 };
var results = data.Skip(recordCount).Take(2);
//Increment recordCount by the count of the results return above
recordCount+= results.Count();
if (results.Count() > 0)
{
//return results
}

Call javascript function from asmx

I want to return javascript function from asmx as string like following..
All html tags return but checkNewMsg variant 'script tag' doesnt return!
What happens really ?
Please advice
<script type="text/javascript">
function getWindow(FromUserID, UserID, PerID, UserName) {
$.ajax({
type: "POST",
url: "TestMessageService.asmx/OpenWindow",
data: "{'FromUserID': '" + FromUserID + "', 'ClickedUserID': '" + UserID + "', 'ClickedPerID': '" + PerID + "', 'ClickedUserName': '" + UserName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var msgs = response.d;
$('#div_Panel').append(msgs).fadeIn("slow");
var elements = $('.panelContent');
for (var i = 0; i < elements.length; i++) {
elements[i].scrollTop = elements[i].scrollHeight;
}
},
failure: function (msg) {
$('#div_Panel').text(msg);
}
});
}
</script>
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string OpenWindow(string FromUserID, string ClickedUserID, string ClickedPerID, string ClickedUserName)
{
string checkNewMsg = "<script type=\"text/javascript\">window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }</script>";
StringBuilder sb = new StringBuilder();
sb.Append(checkNewMsg + "<div class=\"ch_Box\">");
sb.Append("<div class=\"ch_Header\">");
sb.Append("<div style=\"float:left;margin-top: 9px;margin-left: 8px;\"><img src=\"Images/Status.png\"></div>");
sb.Append("<div id=\"roomUsers\" class=\"ch_HeaderItem\">" + ClickedUserName + "</div>");
sb.Append("<div onclick=\"closePanel(this)\" style=\"width: 23px; height: 27px; cursor: pointer; position: absolute; margin-left: 232px;\"><img style=\"height: 20px; margin-top: 4px;\" src=\"Images/close.png\"></div>");
sb.Append("<div id=\"cont_" + ClickedUserID + "\" class=\"panelContent\">" + FillMessages(roomID, FromUserID.ToInt()) + "</div>");
sb.Append("<div class=\"ch_Text\">");
sb.Append("<input id=\"msg_" + FromUserID + "_" + ClickedUserID + "_" + ClickedPerID + "_" + roomID + "\" type=\"text\" class=\"inp\" onkeypress=\"PushText(this)\" autocomplete=\"off\" /></div>");
sb.Append("</div></div>");
return sb.ToString();
}
I don't know why doesn't return script tag an asmx but when i remove the tag and then in the js side while i add script' tag before return value the problem is solved.
Just like this;
In asmx side;
string checkNewMsg = "window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }#func#";
In Js Side;
success: function (response) {
var msgs = response.d;
var arrCont = msgs.split('#func#');
var MsgCont = "<script type=\"text/javascript\">" + arrCont[0] + "<\/script>";

How to use ScriptManager.RegisterStartupScript in a WebMethod in asp.net?

I have a condition where i need to call a jquery function using a webmethod as below:
[WebMethod]
public static void BindData(String Site)
{
String HTML = "";
Int32 i = 1;
DataTable dt = new DataTable();
dt = obj.GetAll(objprop);
if (dt.Rows[0]["UserId"].ToString() != "0")
{
foreach (DataRow item in dt.Rows)
{
string Email = Bal.Common.Decryptdata(item["Email"].ToString());
string SentInvitation = item["SentInvitation"].ToString();
SentInvitation = SentInvitation.ToString() == "1" ? "Already Invited" : "";
if (i % 2 == 0)
HTML += "<div class=~other_wish_row2~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";
else
HTML += "<div class=~other_wish_row3~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";
i = i + 1;
}
ScriptManager.RegisterStartupScript((Page)(HttpContext.Current.Handler), typeof(Page), "hdrEmpty1", "Test('" + HTML + "');", true); return;
}
else
{
}
}
Jquery Code is:
function Test(data) {
alert('hi');
}
function Binddata(SocialSite) {
$.ajax({
type: "POST",
url: "InviteFriends.aspx/BindData",
data: "{SocialSite:'" + SocialSite + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}
});
}
I am not able to fire Test(), please help to resolve this.
You can't do this from a web service (either an .asmx file or a WebMethod) as it does not run in the context of a normal page. I see you're using AJAX, you'll have to do the handling in the success callback method of your jQuery.ajax() call, like so:
function Test(data) {
alert('hi');
}
function Binddata(SocialSite) {
$.ajax({
type: "POST",
url: "InviteFriends.aspx/BindData",
data: "{SocialSite:'" + SocialSite + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Test(data);
}
});
}

When i try send data from server to client nothing happened

Nothing happaned when i try do this in release mode but in debug mode all work fine - why???
When i adding button and outputing data by clicking this buton.My inner links in my list rows work fine also ( http://clip2net.com/s/2AG04 ).And only on $(document).ready(function () { event this doesn't want to work...
On client i have:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index", "Product")',
cache: false,
type: 'GET',
dataType: 'json',
proccessData: false,
contentType: 'application/json; charset=utf-8'
});
On server i have this:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//Отправляем на клиент данные
_senderHub.SendMessage();
return null;
}
return View();
}
Also on server:(SignalR)
readonly ManagerDB _managerDB = new ManagerDB();
public void SendMessage()
{
IEnumerable<ProductModels> list = _managerDB.GetListOfProduct1();
var listToClient = new List<ProductModels>();
foreach (var prod in list)
{
listToClient.Add(new ProductModels
{
Id = prod.Id,
Name = prod.Name,
LockType = prod.LockType,
LockTime = prod.LockTime,
LockUser = prod.LockUser,
TimeStampF = prod.TimeStampF
});
}
var anonimProduct = listToClient;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SenderHub>();
context.Clients.AddListRows(anonimProduct);
}
On client(SignalR) trying catch this data:
$(function () {
var senderHub = $.connection.senderHub;
senderHub.AddListRows = function (data) {
var dataFromServer = data;
var listOfData = "";
for (var i = 0; i < dataFromServer.length; i++) {
$("#ListOfProductsTableBody").html(null);
var userId = '';
if (dataFromServer[i].LockUser != null) {
userId = dataFromServer[i].LockUser;
}
listOfData += ("<tr><td>" + dataFromServer[i].Id + "</td><td>" + dataFromServer[i].Name + "</td><td>" + userId + "</td><td>" + dataFromServer[i].LockType + "</td>" + "<td id=\"ModifyBlock\"><a id=\"Detail\" href=\"#\" alt=" + dataFromServer[i].Id + " >Детально</a>|<a id=\"Delete\" href=\"#\" alt=" + dataFromServer[i].Id + " >Удалить</a>|<a id=\"Edit\" href=\"#\" class=\"" + dataFromServer[i].LockTime + "\" alt=" + dataFromServer[i].Id + " >Редактировать</a></td></td></tr>");
}
$("#ListOfProductsTableBody").append(listOfData);
};
$.connection.hub.start();
});
emphasized text
See David Fowler's response to my question. Looks like you have the same issue.
Server to client messages not going through with SignalR in ASP.NET MVC 4

how to fetch return values between jquery functions and post ajax jquery request to webservice

I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}

Categories

Resources