Error in Focus on textbox using asp.net web appln - asp.net

In the below code i have a textbox when focus comes to my textbox it should call serverside codebehind file using ajax but in my case i can get success alert but it is not moving to serverside and return the value pls help me to fix the issue.
code:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg); //awesome, it works!
},
error: function (xhr) {
}
});
});
});
</script>
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" ClientIDMode="Static" OnTextChanged="txtField_TextChanged"></asp:TextBox>
codebehind
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
return "awesome, it works!";
}

You function should look like the following
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
return "awesome, it works!";
}
Here is a sample link
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Related

How to update <%=Convert.ToString() %> using update panel in asp.net C#

I want to update the test variable through ajax & C# backend code. I have set test variable as string builder in .cs file & want to update the value of the same variable through .cs code using ajax while clicking on div tag.
Code in .aspx:
<asp:UpdatePanel ID="upre" runat="server">
<ContentTemplate>
<%=Convert.ToString(test) %>
</ContentTemplate>
</asp:UpdatePanel>
Ajax code:
$(".mb-2").click(function (e) {
$.ajax({
type: "POST",
url: "one.aspx/Subscribe",
contentType: "application/json; charset=utf-8",
data: '{"name":"test","email":"test#gmail.com"}',
dataType: "json",
success: function (msg) {
if (msg.d) {
alert(msg.d);
}
},
error: function (req, status, error) {
alert("Error try again");
}
});
return false;
});
Backend Code:
[WebMethod]
public static string Subscribe(string name, string email)
{
AllApps abc = new AllApps();
abc.iPriceFrom = 50;
abc.iPriceTo = 100;
abc.test();`enter code here`
return "thanks " + name + ", your email " + email + " is subscribed to our newsletter.";
}
I tried with the above code but it is not updating the variable value at the front side. Data is updating from backend (.cs) file. I want to update the test variable through ajax & C# backend code. I have set test variable as string builder in .cs file & want to update the value of the same variable through .cs code using ajax while clicking on div tag.

Call a function in code behind without using javascript

i am calling a function on onclick, onmousemove and onkeypress event in form tag and the function is in code behind but the method is not executing when user clicking, pressing a key and moving mouse on form1. The code is :
<form id="form1" runat="server" onclick="idletime()" onkeypress="idletime()" onmousemove="idletime()">
.cs file :
protected void idletime(object sender, EventArgs e)
{
Response.Write("hello.");
}
You can use ajax to do that. I am writing down some rough sample code. Hope it may help.
<form id="form1" runat="server" onclick="idletime()" onkeypress="idletime()" onmousemove="idletime()">
<script>
function idletime() {
$.ajax({
type: "POST",
url: "demo.aspx/functionName1",
data: "{parameter1:'" + param1 "',parameter2:'" + param2 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
}
</script>
c# code
using System.Web.Services; --- use this class
[WebMethod]
public static string functionName1(string parameter1, string parameter2)
{
------------------------------;
return "Demo";
}

Calling asp.net server function using jquery ajax

Am basically new to jquery. I have a function in aspx code bihind. I need to call it in a button click from aspx page using jquery. The server side function takes no arguement and returns no data.
The function the code behind is :
[WebMethod]
public void BindTreeview()
{
TreeView1.Nodes.Clear();
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(#"C:\ClientDocuments\Ford Retail Ltd\");
// output the directory into a node
TreeNode RootNode = OutputDirectory(RootDir, null);
// add the output to the tree
TreeView1.Nodes.Add(RootNode);
//TreeView1.SelectedValue = hdnSelectedNode.Value;
if (hdnSelectedNode.Value != string.Empty)
{
TreeView1.CollapseAll();
TreeNode searchNode = TreeView1.FindNode("Electricity");
if (searchNode != null)
searchNode.Expand();
}
}
aspx jquery is
$(document).ready(function () {
$('#btnNewFolder').click(function () {
// alert('Clicked');
$.ajax({
url: 'Default.aspx/BindTreeview',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert(1);
},
error: function (result) {
alert("The call to the server side failed. " + result.responseText);
}
});
});
});
When i run appln am getting alert on result.responseText. Where am i getting wrong? Quick response will be highly appreciable.
mark your method as static
public static void BindTreeview()

Viewdata not showing in partial view

Hi guys i have controller which returns a partial view, the controller is called by ajax script. The partical view has no problem showing viewdata first time, But when ajax script is invoked second time the partical view does not update it self with new viewdata.
code for controller
[HttpGet]
public ActionResult getPart(int id)
{
ViewData["partical"] = id;
return PartialView("test");
}
code for partial view
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PovertyBayHotel.Models.testmodel>" %>
<p>just a test</p>
<%: ViewData["partical"]%>
and the ajax which call the controller
<script type="text/javascript">
$(document).ready(function () {
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
});
});
</script>
Might be a caching issue. Try HTTP POST instead of GET or set the ifModified and cache options to false as below:
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
ifModified: false,
cache: false,
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
Also, try to debug your code and see really what is going on.
Edit:
The problem has been solved by changing $('#ExtraBox').replaceWith(data); with $('#ExtraBox').html(data);.

Ajax success when a view is returned

I'm struggling to return a view or partial view with Ajax. Whenever I change the return type to something that isn't JSon the ajax command never succeeds. I need to return a partial view because I want to return a lot of data back.
This is my current code:
(Controller)
[HttpPost]
public ActionResult AjaxTestController(string Input)
{
string Results = Input + " -- TestTestTest";
return PartialView("Test", Results);
//return new JsonResult() { };
}
(View)
function AjaxTest() {
alert("test");
$.ajax({
type: "POST",
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function () {
alert("Success!");
}
});
Thanks!
You can use the $.post command for that:
function AjaxTest() {
alert("test");
$.post({
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function (response) {
alert(response);
}
});
try the following:
$(function () {
$('#submit').live('click', function () {
AjaxTest();
});
});
function AjaxTest() {
$.ajax({
type: "POST",
url: '#Url.Action("AjaxTestController", "Home")',
data: { Input: "Test - " + new Date() },
success: function (data) {
$('#partialResult').html(data);
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
};
inside your view and ensure that you have your target div set up for the partial to be populated into:
<div id="partialResult"></div>
also, for the example above, I added a button to the view to initiate the ajax (purely for testing):
<input type="button" value="Submit" id="submit" />
your 'partialview' should look something like this:
#model string
<h2>
Partial Test</h2>
<p>
#Model
</p>
no other changes are required to the existing action for this to now function as required.
[UPDATE] - I changed the AjaxTest() method to include the error event (the result of which is captured in an alert). hopefully, this may help further.
partial View is different than view you have to specify the whole path to the partial view or have it in share folder. otherwise is going to return not found and never success. any way this always work for me, try
partialView("~/Views/ControllerView/Test.cshtml")

Resources