I was wondering if it is possible to pass the forms collection from within an ajax method in jQuery?
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});
If it is possible to pass in the forms collection then when it arrives at the method within c# how to you read it in?
You can do something like this:
var form = $("#myForm").serialize();
$.post("/Home/MyUrl", form, function(returnHtml)
{
//callback
});
Then on the C# side you should be able to do something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyUrl(FormCollection collection)
{
//do what you gotta do
}
I think this should work.
EDIT: I just noticed that I simply assumed you were referring to ASP.NET MVC. If not, let me know as this answer is specific to MVC.
You can use the Ajax.BeginForm method from ASP.NET MVC. It will use Microsoft's ajax to do the request, but you can have a JQuery method execute upon completion. Or you can use an UpdatePanel and register a javascript to run with the ScriptManager once the UpdatePanel loads. Another thing you could try is using a jquery like the following: $(':input') to get a collection of all input, textarea, select and button elements(JQuery documentation), and pass that as the data into your request.
Got this working all okay, and it returns the input form collection in the FormCollection
input = $(':input')
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: input,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});
Related
i want to call the unlock method on closing or redirecting other page, so i have used ajax call. but the method unlock is not firing. please let me know what i am doing
[WebMethod]
public void Unlock()
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;
Where you passing project_id in your ajax call???
pass project_id in your method
[WebMethod]
public void Unlock(string project_id)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
and then rewrite ajax call as
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
data : "{project_id:'1234'}",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;
There's a couple of issues. Firstly your WebMethod expects a querystring parameter, yet you're sending a POST request and you also don't send any data in the request. You should provide project_id as a parameter in an object to the data property of the AJAX request.
Also note that sending an AJAX request in the onbeforeunload event is one of the very few legitimate cases where you need to use async: false to stop the page from being closed before the AJAX request completes. Try this:
[WebMethod]
public void Unlock(string projectId)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(projectId), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
async: false, // only due to running the code in onbeforeunload. Never us it otherwise!
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { projectId: '1234' }
});
}
window.onbeforeunload = HandleOnclose;
Also note that depending on the browser you may be restricted from sending an AJAX request in the onbeforeunload event at all. See this question for more details.
I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!
try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});
In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.
Iam having a UserControl for showing Success/Warning/Error message. For all these kind of messages we have one UserControl "Message.ascx" Currently using for other aspx pages without Jquery
As we are trying to maintain standard message alerts.
Now as iam using Jquery and JSON calls in my aspx page for the first time., i want to show these success message from my jquery.,
In general aspx codebehind i have used the User control as
//register User Control
<UM1:UM runat="server" ID="Message" />
....
public void insert(){
.. Some logic.., after success
Message.ShowSuccess(" Inserted Successfully");
}
But here in Jquery how do i call these ShowSuccess() which is in ascx.cs
my ajax call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Voyage.aspx/Context_Update",
data: "{'ID':''1}",
dataType: "html",
success: function (html) {
try {
// Want to Show Message.ShowSuccess(" Inserted Successfully");
} catch (ex) {
alert("ErrCode:1");
}
Iam not getting any idea and have not found any results too..,
Please help me out
You can't make a call to a User-Control in ASP .NET as it isn't something that is directly served to the outside world but instead something that the server combines into your page during the page life-cycle.
If you want to call something on the server you need to add the [WebMethod] attribute to the server side method, this allows you to call from jQuery. You could have a [WebMethod] on your page that then calls some code in your User-Control, but not directly access your User-Control.
So, something like this:
MyPage.aspx
[WebMethod]
public static string GetMessageFromWebPage()
{
return MyUserControl.GetMessageFromUserControl();
}
MyUserControl.ascx
public static string GetMessageFromUserControl()
{
return "Hello World!"
}
jQuery
$.ajax({
type: "POST",
url: "MyPage.aspx/GetMessageFromWebPage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something with the page method's return.
$("#Result").text(msg.d);
}
});
I am trying to build an asp.net(c#) page that updates some state texts every second.
Now I have implemented an button that calls another PageMethod which restarts something and takes a little while. The problem is, that when I call the restart PageMethod , the update PageMethod can't update as long as the restart method is proceeding...
I wrote a little example to show what I mean:
WebMethods in my Page:
[WebMethod]
public static string Update()
{
//return "a" to see when the Update PageMethod succeeded
return "a";
}
[WebMethod]
public static string Restart()
{
//the restart will take a while
Thread.Sleep(2000);
//return "a" to see when the Restart PageMethod succeeded
return "a";
}
the html elements to update:
<p id="update" style="float:left;"></p>
<p id="restart" style="float:right;"></p>
the Pagemethod calls:
callUpdate()
function callUpdate() {
PageMethods.Update(function (text) {
//itself+text from pagemethod
$('#update').text($('#update').text() + text);
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
PageMethods.Restart(function (text) {
//itself+text from pagemethod
$('#restart').text($('#restart').text() + text);
});
setTimeout(callRestart, 1000);
}
Note: The Update is also called every second after it finished, just to see how it works
To clarify: I want the PageMethods to execute independent to that the other PageMethod has finished.
I also flew over some links like:
http://esskar.wordpress.com/2009/06/30/implementing-iasyncresult-aka-namedpipeclientstream-beginconnect/
http://msdn.microsoft.com/en-us/library/aa480516.aspx
But I don't think this is what I need (?)
And I really don't know how to call that from Javascript (BeginXXX and Endxxx)
*EDIT: *
Regarding to Massimiliano Peluso, the js code would look like this:
callUpdate()
function callUpdate() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Update",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#update').text($('#update').text() + msg.d);
}
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Restart",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#restart').text($('#restart').text() + msg.d);
}
});
setTimeout(callRestart, 1000);
}
Note: when I run the Page with the new js, there is exactly the same problem as before: The Update method can do nothing until the Restart method is finished.
you should call the page methods using an Async call instead.
have a look at the below. It is a generic way to call a page method using JQuery
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
you should use this code to replace the page method calls
PageMethods.Restart(function (text))
PageMethods.Update(function (text))
It's because an Request only Proceeds when no other Request is processing.
Thats because two Processes can't acess to the same SessionState (Sessionstate is not Threadsafe).
So to achieve that Requests are processed at the same time, you have to set EnableSessionState in the #Page directive to either 'ReadOnly' or 'false'
I have a user control that I'm creating that is using some AJAX in jQuery.
I need to call a function in the code-behind of my control, but every example I find online looks like this:
$("input").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//do something
}
});
});
This works fine if I have the method in the Default.aspx page. But I don't want to have the function there, I need the function in the code-behind of my control. How can I modify the url property to call the correct function?
I tried:
url: "GetResult"
but that didn't work.
The way to handle this is to have the webmethod in your page, then just pass the values directly to a control method with the same signature in your control - there is no other way to do this.
In other words, ALL the page method does is call the usercontrol method so it is really small. IF you have the same signature for multiple child controls, you could pass a parameter to tell the page method which one to call/use.
EDIT: Per request (very very simple example). You can find other examples with more complex types being passed to the server side method. for instance see my answer here: Jquery .ajax async postback on C# UserControl
Example:
Page method: note the "static" part.
[WebMethod]
public static string GetServerTimeString()
{
return MyNamespace.UserControls.Menu.ucHelloWorld();
}
User Control Method:
public static string ucHelloWorld()
{
return "howdy from myUserControl.cs at: " + DateTime.Now.ToString();
}
Client ajax via jquery:
$(document).ready(function()
{
/***************************************/
function testLoadTime(jdata)
{
$("#timeResult").text(jdata);
};
$("#testTimeServerButton").click(function()
{
//alert("beep");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "MyPage.aspx/GetServerTimeString",
success: function(msg)
{
testLoadTime(msg);
}
});
});
});
Note: the dataFilter: function(data)... part of the ajax is so that it works with 2.0 and 3.5 asp.net ajax without changing the client code.
You can't...WebMethods have to be in WebServices or Pages, they cannot be inside UserControls.
Think about it a different way to see the issue a bit clearer...what's the URL to a UserControl? Since there's no way to access them you can't get at the method directly. You could try another way perhaps, maybe a proxy method in your page?