Calling to c# function from javascript function - c#

I have a javascript function and c# fanction. I need to call to the c# function from the javascript function, but I don't know how...
Can someone help me?
Thank you!
The javascript function-
<script type="text/javascript" language="javascript">
function DeleteBook(idimg) {
// idimg is a string
var userConfirm = window.confirm('Are you sure?');
if (userConfirm == true) {
control.Sess(idimg);// The line which is colling to the c# function - doesn't work
window.open('Delete.aspx');
}
else
return false;
}
</script>
The c# function-
protected void Sess(string id)
{
Session["forDelete"] = id;
}

You can create a web method
[WebMethod(EnableSession = true)]
public static Application GetApplication(int id)
{
}
and in javascript you then do something like this
$.ajax(
{
type: "POST",
url: "Applications.aspx/GetApplication",
contentType: "application/json; charset=utf-8",
data: "{'id':" + id + "}",
dataType: "json",
success: methodToDoSomethingOnSuccess,
error: function (rhq, textStatus, errorThrown) {
alert ("some went awry");
}
});

you have to create an input of type submit that invokes your C# function using the HTML and make it hidden. Then create a div tag and using javascript do this:
#CSS
.Hidden {
display:none;
}
#HTML
<input type="submit" id="SubmitTag" OnClick="C# Functin" class="Hidden" runat="server" />
//if using MVC and Razor
#using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post)) {
<input type="submit" id="SubmitTag" class="Hidden" />
}
<div id="OnDivClick"> what you want to do in here </div>
#JS
$('#OnDivClick').click(function () {
$('#SubmitTag').trigger("click");
});

Well, there are ways to do this but I believe that you're trying to save something in the Session for the Delete.aspx page to read it. The simplest solution is just post the data in:
var form = document.createElement("form");
form.setAttribute('method', 'post');
form.setAttribute('action', 'Delete.aspx');
form.setAttribute('target', '_blank');
form.innerHTML = '<input type="hidden" name="forDelete" value="' + idimg + '" />';
document.body.appendChild(form);
form.submit();
This dynamically creates a form and submits it with idimg which will open the page Delete.aspx in a new window.
All that's left to do is go to the C# part of Delete.aspx page and catch the incoming data:
string idimg = Request.Form["forDelete"];
// Do whatever with it
Session["forDelete"] = idimg; // If you still want to save it in Session

Related

Ajax using JQuery in ASP .NET c#

I am trying to use JQuery ajax in asp .net c#. The code I am using is ...
HTML FORM:
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
JQuery Part :
<script type="text/javascript">
function ShowCurrentTime() {
//alert(window.location.pathname);
$.ajax({
type: "POST",
url: "Display.aspx/GetCurrentTime",
data: '{name: "' + $("#< %=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
CS PArt:
using System.Web.Services;
This part below is under partial class which inherits from Page class.
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello "+ name +"! " + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Problem:
It is not working. Please let me know if I am missing any setting or any name space. Or any thing. URL I Put in ajax Call is correct as I verified it by
var pathname = window.location.pathname; I supplied data also while calling ajax.
Maybe changing
failure: function (response) {
alert(response.d);
}
to
error: function (response) {
alert(response.d);
}
Will help find the issue.
I don't see a failure callback in the docs - http://api.jquery.com/jquery.ajax/
The things I can see right off the bat:
$.ajax doesn't take a "failure" parameter, but rather "error." Even
then, you should be using .done() and .fail() instead (see
http://api.jquery.com/jQuery.ajax/)
Your error handling function will be triggered when your page method
throws an exception. The first parameter is a jqXHR object, not a
JSON response from .NET (see the same link as from #1).
Your page method should not go UNDER the page class, but within it.
JQuery has some error
$("#< %=txtUserName.ClientID%>")[0].value
need to be
$("#<%=txtUserName.ClientID%>")[0].value
or
$("#<%=txtUserName.ClientID%>").val()

Autocomplete does not showing the results from controller in asp.net MVC

The autocomplete code written is getting the results from controller and is also showing when used F12 developer network tab with the browser. But the actual returned result is not showed by the textbox, only drop-down with no values are shown.
I'm including the codes of view and controller. Please help me out to solve this.
code of the view page :
<html>
<head><title></title>
<link href="~/Content/themes/base/jquery.ui.autocomplete.css" rel="stylesheet" />
<script type="text/javascript" >
$(document).ready(function () {
alert("hi");
$("#ValueField").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Customer/AutoretrieveCustomer",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
var items = $.map(data, function (item) {
return {
label: item.FirstName,
value: item.FirstName
};
});
response(items);
}
})
}
});
});
</script>
</head>
<body>
<div id="CusView">
<label for="FirstName">Enter Customer First name : </label>
Enter value : <input type="text" id="ValueField" />
</div>
</body>
</html>
code of the controller :
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AutoretrieveCustomer(string term)
{
Banking.BankingDBEntities db = new BankingDBEntities();
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Also I would need the code for getting the id of the user selected item in the textbox.
The following the output pic when the autocomplete is executed
This bit in your controller action:
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
Means that your controller action is actually returning an array of strings, not an array of objects like your success function is assuming.
You should be able to remove the mapping and just call response directly with the array of strings:
success: function (data) {
response(data);
}
Or, just:
success: response

Construct div pattern using Ajax Json

I'm going to use owl carosel.In the hardcoded div's working.Now i want to get this type via ajax function.I'll try to do this in several ways but not success.
My Webmethod it returns the Image Path & Caption values.
<div id="owl-demo">
<div class="item"><a class="item link"><img src="/Content/images/sdfdfd.png" alt="Owl Image"></a><p><center>CAPTION</center></p></div>
<div class="item"><a class="item link"><img src="/Content/images/tyty.png" alt="Owl Image"></a><p><center>CAPTION</center></p></div>
</div>
My Ajax function(instead of that hardcoded values )
function GetAllImages()
{
$.ajax({
type: "POST",
url: "/Dest/GetAllImages",
success: function (msg) {
debugger;
if (msg._allImg.length > 0) {
$.each(msg._allImg, function (index, item) {
//In here i need to construct that above pattern
//My Webmethod it returns the Image Path & Caption values.
var html = $("<div>").html();
var html2 = $("<img src").html();
$('#owl-demo').append(html);
});
}
else {
}
}
});
}
If I follow you, I think you mean:
$('#owl-demo').append('<div class="item"><a class="item link"><img src="/Content/images/' +
item.url + '" alt="Owl Image"></a><p><center>' +
item.caption + '</center></p></div>');

Fetching Cities dynamically in Asp.net HTML control

I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}

Jquery click event not firing after getting json data

I'm working on an Asp.Net MVC3 application, using jQuery. On a specific page, the user is invited to enter the telephone number to search for a company. So, there is a result (_Result partial view) whitch I get by using json when clicking on the Search button.
On an other part, if the result is on multiple pages, when the user click the "Next button", nothing happen. Knowing that if I click on the Next button before clicking on the Search button, I have my click event fired.
The Next button is in the _Result partial view.
Here's my code HTML / Razor :
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
In the _Result partial view
<div>
<span>Page N sur M</span>
<input id="bnPreviousPage" type="submit" value="Précédant" name="bnPrevious"/>
<input id="bnNextPage" type="submit" value="Suivant" name="bnNext"/>
</div>
Here's my JS code :
<script type="text/javascript">
$(document).ready(function ()
{
$("#idBnSearch").click(function ()
{
var telValue = $("#idTxTel").val();
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
doReverseSearch(telValue, 0, methodUrl);
});
$("#bnNextPage").click(function (e)
{
alert("Next cmd");
});
});
</script>
My "doReverseSearch" method in an other JS file
function doReverseSearch(telValue, pageIdx, methodUrl)
{
$.ajax(
{
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
Thanks in advance
The problem is that you subscribe on the #bnNextPage click event when the document is ready but in your ajax success you replace the part of the DOM where #bnNextPage was originally.
So your click subscription is now loger active, that's way it only works if you haven't searched yet.
To make it work you need to resubscribe on the click event in the ajax success:
success: function (data) {
$('#result').replaceWith(data);
$("#bnNextPage").click(function (e)
{
alert("Next cmd");
});
},
Or as far more better solution: JQuery offers "durable" subscription with the live method. If you modify your original click code:
$("#bnNextPage").click(function (e) { alert("Next cmd"); });
to
$("#bnNextPage").live("click", function (e) { alert("Next cmd"); });
It will work without modifying your success callback.
Please note that as JQuery 1.7 the live method is deprecated and you should use the on method instead. In your case the subscription looks like the following with on:
$(document).on("click", "#bnNextPage", function (e) { alert("Next cmd"); });

Categories

Resources