Calling a linkbutton click with jquery - c#

I've got a textbox, I want a function to be called onkeyup, for that reason I've got a hidden button that is trying to redirect to another c# function. The problem is jquery goes inside the function, but then doesn't go to the server side event.
Here's my HTML for both elements:
<div class="row" style="margin-top: 5px;">
<div class="col-sm-12">
<div class="input-group input-group-sm">
<span class="input-group-addon">Име:</span>
<asp:TextBox ID="tbCliName" ClientIDMode="Static" runat="server" onkeyup="runQuery(this)" CssClass="form-control"></asp:TextBox>
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
<span class="input-group-addon">Егн/Булстат:</span>
<asp:TextBox ID="tbEgnBStat" ClientIDMode="Static" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
</div>
Here's my jquery funtion:
function runQuery(e) {
$('#hiddenButton').click();
}
And the C# for the button click:
protected void hiddenButton_Click(object sender, EventArgs e)
{
AutoComplete_Press(tbCliName.Text);
}
EDIT with Ajax:
function runQuery(e) {
var search = $(e).val();
function runQuery(e) {
var search = $(e).val();
var params = {
url: 'addEditProduct.ascx/AutoComplete_Press',
method: 'post',
contentType: 'aapplication/json',
data: '{searchClause:' + search + '}',
dataType: 'json',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
};
$.ajax(params);
}
[WebMethod]
public static void AutoComplete_Press(string searchClause)
{
int searchType = 0; //ЕГН
int csKind = 0;
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(searchClause))
searchType = 1;
//if (rbLP.Checked)
// csKind = 1;
string clients = laboratory.getClients2(searchType, searchClause, 1);
}

try using webmethod. In server side
[WebMethod]
public static void BindData()
{
AutoComplete_Press(tbCliName.Text);
}
And in client side
$("#hiddenButton").click(function() {
$.ajax({
type: "POST",
url: "index.aspx/BindData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({/*pass values here*/}),
dataType: "json",
});
});
Refer below link
https://www.aspsnippets.com/Articles/Calling-server-side-methods-using-JavaScript-and-JQuery-in-ASP.Net.aspx

The reason why it is not working is that you are using asp:LinkButton which is rendered as a element with href attribute set to javascript:__doPostBack().
If you replace asp:LinkButton to asp:Button calling $('#hiddenButton').click(); will start to work.
Just change this line of code
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
to this
<asp:Button ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:Button>

You can invoke function like this but not event
Create a Web Method and try Jquery Ajax
var params = {
url: 'Index.aspx/YourWebmethod',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: JSON.stringify(data to be send ),
success: function (result) {
alert('Success');
},
error: function (result) { alert('Warning! It failed.'); }
};
$.ajax(params);

Related

Delete all checked element in list

I display a list of element from a list, and I have to display a checkbox in front of each element, and then delete all checked element, I wrote a jquery code for do this but it removes just the first element checked, how I should do to remove all checked items
<button type="submit" class="btn fsc-btn-3" id="AllDelete">
<i class=" fa fa-check"></i>
<span>#Labels.Global_DeleteSelection</span>
</button>
#foreach (var item in Model.FilesList)
{
<tr>
<td><input type="checkbox" name="checkFile" id="checkFile" value="#item.FileId" /></td>
<td>#item.ArrivalTime</td>
<td>#Model.TraitementDate(item.FileId)</td>
<td>#item.Name</td>
<td>#item.FileType</td>
<td>
<label class="proj-label-1 proj-label-size-1 proj-status-5" title="#item.State">
<i class="fa fa-check-circle"></i>
<span>#item.State</span>
</label>
</td>
<td >#item.NumAlertRecords</td>
<td>#item.NumRejectedRecords</td>
<td >#item.NumAcceptedRecords</td>
}
jQuery code:
(function(jQuery) {
jQuery(function() {
jQuery('#AllDelete').click("click", function() {
jQuery('input[type="checkbox"]').each(function() {
if (jQuery(this).is(':checked')) {
alert(jQuery("#checkFile").val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery("#checkFile").val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);
Controller :
[HttpPost]
public ActionResult DeleteMultiCredit(int FileId)
{
DeleteCreditModel model = new DeleteCreditModel();
model.Delete(FileId);
return RedirectToAction("Index");
}
Try this : first of all you cannot use same id for all checkbox, so either generate unique ids for each one or remove id attribute
#foreach (var item in Model.FilesList)
{
<tr>
<td><input type="checkbox" name="checkFile" value="#item.FileId" /></td>
<td>#item.ArrivalTime</td>
<td>#Model.TraitementDate(item.FileId)</td>
<td>#item.Name</td>
<td>#item.FileType</td>
<td>
<label class="proj-label-1 proj-label-size-1 proj-status-5" title="#item.State">
<i class="fa fa-check-circle"></i>
<span>#item.State</span>
</label></td>
<td >#item.NumAlertRecords</td>
<td>#item.NumRejectedRecords</td>
<td >#item.NumAcceptedRecords</td>
}
now use $(this).val() to get value of each checkbox instead of using id of checkbox to read value
jQuery(function () {
jQuery('#AllDelete').click("click", function () {
//you can use :checked directly in selector, so if condition not required
jQuery('input[type="checkbox"]:checked').each(function() {
alert(jQuery(this).val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },//read your value here
success: function (data) {
}
});
});
});
})(jQuery);
Use jQuery(this) instead of jQuery("#checkFile")
Just like this :
(function(jQuery) {
jQuery(function() {
jQuery('#AllDelete').click("click", function() {
jQuery('input[type="checkbox"]').each(function() {
if (jQuery(this).is(':checked')) {
alert(jQuery(this).val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);
try below code
jQuery(function () {
jQuery('#AllDelete').click(function () {
jQuery('input[type="checkbox"]').each(function() {
if(this.checked){
alert(jQuery("#checkFile").val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);

jQuery progress bar until save in database asp.net

In an Asp.Net application I need the jQuery progress bar that runs till the data is not saved in database
For this I created a web service and the Ajax jQuery function and the progress bar Javascript plugin
HTML
<div id="progressbar"></div>
<div id="result"></div>
<asp:Label runat="server" ID="lbldisp" Text= "Percentage Completed : "/>
<asp:Label runat="server" ID="lblStatus" />
<asp:Button ID="btnSave" runat="server" Text="Save" class="buttonstyle" />
Script (I am using Sys.Application.add_load instead of document.ready function due to DOM Interruption )
<link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script src="js/ui.core.js" type="text/javascript"></script>
<script src="js/ui.progressbar.js" type="text/javascript"></script>
<script type="text/javascript">
Sys.Application.add_load(function() {
// jquery Progress bar function.
$("#progressbar").progressbar({ value: 0 });
$("#lbldisp").hide();
//button click event
$("#ctl00_ContentPlaceHolder1_btnSave").click(function() {
$("#ctl00_ContentPlaceHolder1_btnSave").attr("disabled", "disabled")
$("#lbldisp").show();
//call back function
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "JobCard.aspx/InsertData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#progressbar").progressbar("value", 100);
$("#lblStatus").hide();
$("#lbldisp").hide();
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
$("#lblStatus").text((value + 1).toString() + "%");
}
}
</script>
Web service
[System.Web.Services.WebMethod]
public static string InsertData()
{
fortest jobcardForm = new fortest();
//this is a line 760 --> jobcardForm.Insert_OilService();
jobcardForm.Insert_TuningService();
jobcardForm.Insert_OtherServices();
jobcardForm.Insert_QRCService();
jobcardForm.Insert_problemTaken();
jobcardForm.Insert_ActionTaken();
jobcardForm.Insert_SpareParts();
//Insert_Technician();
dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter insertjobcard = new dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter();
string a = insertjobcard.Insert_JobCarRegistration(
jobcardForm.txtdate.Text, jobcardForm.txtTimeIn.Text,
jobcardForm.txtTimeOut.Text, jobcardForm.Txt_RegNo.Text,
jobcardForm.Txt_FleetNo.Text,
jobcardForm.chkbkdvechle.Checked, jobcardForm.chkwalkin.Checked,
jobcardForm.chkRepeatJob.Checked,
jobcardForm.txtCustomerName.Text, jobcardForm.txtRiderName.Text,
jobcardForm.txtPhoneNo.Text, jobcardForm.txtEmail.Text,
Convert.ToInt32(jobcardForm.ddl_ServiceAdvisor.SelectedValue),
Convert.ToInt32((jobcardForm.ListBox1.SelectedValue == "" ? "0" : jobcardForm.ListBox1.SelectedValue)),
jobcardForm.ddl_Model.SelectedValue,
jobcardForm.ddl_type.SelectedValue, jobcardForm.txtKMSRUN.Text,
jobcardForm.ddl_color.SelectedValue
, "1", HttpContext.Current.Session["user_id"].ToString(),
jobcardForm.txtdateout.Text, jobcardForm.txtchassis.Text,
jobcardForm.ddlyear.SelectedValue, jobcardForm.txtexpirydate.Text,
jobcardForm.txtnotes.Text,
jobcardForm.ddllocation.SelectedValue).ToString();
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
return "Save Completed...";
}
Looks like the script is working fine but I am getting an error in the web browser console Window and the error is "500 Internal Server Error" at line 760 in web service jobcardForm.Insert_OilService();. But when I use the web service code in server side onclick event the data is inserted into the database. I need the progress bar, that's why I have to change the logic using web service
ERROR
I normally create an object of a class to use it in a static method and this was the simplest way to use a non-static method in a static method.
Why dont you do something like this:
function FunctionName() {
$.ajax({
type: "POST",
url: ,
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#progress-bar").show();
$("#progress-bar1").hide();
},
complete: function () {
$("#progress-bar").hide();
$("#progress-bar1").show();
},
success: function () {
}
});
}
And have 2 div
<div class="gap"></div>
<div id="progress-bar" style="display:none;">
<img src="~/Images/ajax-progressbar.gif" />
</div>
<div id="progress-bar1"></div>
</div>
So before you send your request you show $("#progress-bar").show(); once once the content loaded you hide it. Hope this answer your question.

How to send files to webmethod along with other data? Without using any plug in

Ok so I have a couple of input fields etc I send the data of these field to server side webmethod . WHich is working fine. But I also want to send files to the same webmethod (and not ashx hander) alond with the data of other input fields. Can you please help me out?
This calls webmethod which stored data in database
function SendToServer(name,lineitems) {
$.ajax({
type: "POST",
url: "test.aspx/PostDataWM",
data: JSON.stringify({ name: name,lineitems: lineitems }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
// console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
File Upload MarkUp
<span style="font-family: Arial">Click to add files</span>
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<br />
<br />
<div id="FileUploadContainer">
<!--FileUpload Controls will be added here -->
</div>
<script type="text/javascript">
var counter = 0;
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" class="clsFileUpload" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>
WebMethod
[WebMethod(enableSession: true)]
public static string PostDataWM(string name,string lineitems)
{
//blah blah
}
No need to stringify the data.
Try it directly. You can get data at your code level
type: "POST",
url: "test.aspx/PostDataWM",
data: { name: name,lineitems: lineitems },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,

Ajax : passing input box value to C# codebehind

I have an AJAX almost working. I can get it to execute a simple function and return a value such as the date and time.
My problem now is developing the script to send the value of an input box to the C# function and then using this value in the code. So that a the correct string can be returned.
If sombody could check if am doing it right or where am going wrong then that would be great
thanks
Ajax Code
$(document).ready(function ste() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
var thePostCode = $('#ContentPlaceHolder1__postCodeInput').val();
$.ajax({
type: "POST",
url: "Add-Property.aspx/GetAverageRent",
data: { PostCode: thePostCode },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
alert("code was executed");
codeAddress();
}
});
});
});
C# Function Code
[WebMethod]
public static string GetAverageRent(string PostCode)
{
string Postcode = PostCode;
var webGet = new HtmlWeb();
var doc = webGet.Load("http://www.webaddress.com" + Postcode);
HtmlNode AvgPrice = doc.DocumentNode.SelectSingleNode("//div[#class='split2r right']//strong[#class='price big']");
if (AvgPrice != null)
{
return AvgPrice.InnerHtml.ToString();
}
else
{
return "Invalid Postcode!";
}
}
Markup
<div class="form-group">
<label for="_postCodeInput">Post Code: </label>
<input type="text" runat="server" id="_postCodeInput" onchange="ste()" class="form-control"/>
<asp:RequiredFieldValidator ID="_pcodeRFV" runat="server" Display="Dynamic" ControlToValidate="_postCodeInput" ValidationGroup="saveProperty" ErrorMessage="Property Postcode" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
<div id="Result">Click here for the time.</div>

How to connect $.ajax-data from textbox input?

I am looking for connect the input i search within textbox, into the $.ajax-data.
textbox id=textSearchTB.
(the whole idea from this function is to press search from textbox input, and display the result)
function getSearchRecipe() {
$.ajax({
url: "WebService.asmx/searchRecipe",
data: "{id:textSearchTB}",
type: "POST",
dataType: 'json',
contentType: "application/json; charset= tf-8",
success: function (data) {
var result;
if (data.hasOwnProperty('d')) {
result = data.d;
}
else {
result = data;
}
for (i = 0; i < result.length; i++) {
$("#searchResult").append("<div>'" + result[i] + "'</div>");
}
}
});
}
<div data-role="content">
<form id="searchF">
<input type="text" id="textSearchTB"/>
<input id="searchRecipeBTN" type="submit" value="חפש מתכון" onclick="getSearchRecipe()" />
</form>
<form id="searchResult">
</form>
</div>
To get the value in the search box, do:
var textInput = $('#textSearchTB').val(); // Jquery
then:
data: {id: textInput} // am assuming that the server side method contains an argument named "id"

Categories