I am trying to use $.ajax.post using:
$.ajax({
type: "POST",
url: "http://localhost/products/SaveXML.aspx",
data: { name: "John", location: "Boston" }
}).done(function (msg) {
alert("Data Saved: " + msg);
});
});
SaveXML lookes like:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="c#" runat="server">
public void testMethod()
{
string sayHello = "hello world";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server"></form>
</body>
</html>
Eventually, I want to pass in some XML and have SaveXML handle it.
Does the code need to be in a code-behind? Does it need to be marked as a web method?
Can someone show me what this should look like please?
Thanks
You can use ASP.NET Page Methods with jQuery.
Check this:
Using jQuery to directly call ASP.NET AJAX page methods
The code needs indeed to be server side code (which doesn't mean you have to have a code behind file - what you have with your testMethod will work just fine, as it is in a server side context).
Since you are posting the data to the .aspx page, there is no need to use a web method. You can use Page_Load or OnInit to get the posted data (via the Request page property) and handle the posted data in it.
Related
Hi,
I have implemented this plugin by Steve Sanders from 2008. In my solution I have 3 buttons for 3 uploads and this works just fine. But ist not a perfect fit and the question is if thera is a better solution for me?
What I need is :
Be able to upload multiple files
When the Control Action is triggered It should be possible to work with the files
The enduser should be able to cancel a uploaded file(this is not possible with Steves plugin as far as I know)
Easy to use with ASP.NET MVC
If a post is done to the Control Action and a validation error is thrown back the uploads may not disappear.
Pleas Advice
How about using Uploadify? I have used it before, and it works great. But do notice that it also needs a Flash front-end in order to work...
Take a look at this StackOverflow question - there you'll find more info of how to use it with ASP.NET MVC.
Under the hood the Steve Sanders' plugin uses swfUpload which can support everything you need. His plugin however does not seem to expose all of the features of swfUpload such as canceling uploads.
I use swfUpload to it's full extent on my sites supporting multiple files, canceling uploads, validation without canceling other uploads, etc.
Here's a demo of swfUpload in action where you can cancel uploads
Another option is SlickUpload.
It's not free but definitely worth it in my opinion. I used it in an MVC project recently and was extremely happy with it. Best upload plugin I've ever used + it comes with all sorts of validation helpers.
It's fully customizable too.
Download the trial and have a look for yourself :)
It's not possible with pure ASP.NET.
You need to take JQuery uploadify.
It's the best you can find, trust me, I tried for an entire day.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="MassUpload.aspx.vb" Inherits="Raumplaner_New.MassUpload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Mass Upload</title>
<link href="../upload/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../scripts/swfobject.js"></script>
<script type="text/javascript" src="../scripts/jquery.uploadify.v2.1.0.min.js"></script>
<script type = "text/javascript">
$(document).ready( function()
{
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader' : '../upload/scripts/uploadify.swf',
'script' : '../cgi-bin/Upload.ashx',
'cancelImg' : '../upload/images/cancel.png',
'folder' : '../upload/temp',
'buttonImg' : '../upload/images/uploadbutton.png',
'width' : '97',
'height' : '22',
'wmode' : 'transparent',
'displayData' : 'speed',
'multi' : true,
'auto' : true,
'simUploadLimit' : 20,
'fileDesc' : 'DWG und SWF - Dateien',
'fileExt' : '*.dwg;*.swf',
'onSelect' : function(event, queueID, fileObj){ EnableObject('FileUpload1');},
'onCancel' : function(event, queueID, fileObj, data){DisableObject('FileUpload1');},
'onComplete' : function(event,queueID,fileObj,response,data){alert(fileObj.name);}
});
$("#startUploadLink").click( function()
{
$('#<%=FileUpload1.ClientID%>').uploadifyUpload();
return false;
});
$("#clearQueueLink").click( function()
{
$("#<%=FileUpload1.ClientID%>").uploadifyClearQueue();
return false;
});
});
</script>
</head>
<body style='background:black;'>
<div id='main'>
<form id="form1" runat="server">
<br/>
<div class="demo">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
Start Upload |
Clear
</div>
</form>
</div>
</body>
</html>
And here's upload.ashx
<%# WebHandler Language="VB" Class="Upload" %>
Imports System
Imports System.Web
Public Class Upload : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = context.Request("folder")
'If you prefer to use web.config for folder path, uncomment below:
'tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
savepath = context.Server.MapPath(tempPath)
Dim filename As String = postedFile.FileName
If Not System.IO.Directory.Exists(savepath) Then
System.IO.Directory.CreateDirectory(savepath)
End If
postedFile.SaveAs((savepath & "\") + filename)
context.Response.Write((tempPath & "/") + filename)
context.Response.StatusCode = 200
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
I'm trying to call a static method in c# using jQuery Ajax. I've tried before but now it is not working. I get error status as 200 Ok. Here is my code:
$("#btnSample").live("click", function()
{
$.ajax({
type : "POST"
, data : {}
, url : "jQueryAjax.aspx/SampleMethod"
, contentType : "application/json; charset=utf-8"
, dataType : "json"
, success : function(msg)
{
alert("Success : "+msg);
}
, error : function(error)
{
$("#lblSample").text(error.status);
}
});
});
My Server-side code is:
[WebMethod]
public static string SampleMethod()
{
return "jQuery is Super";
}
aspx for Button:
<input type="button" id="btnSample" runat="server" value="Show What" />
I've recreated your code on my side.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#btnSample").live("click", function() {
$.ajax({
type: "POST"
, data: {}
, url: "Default.aspx/SampleMethod"
, contentType: "application/json; charset=utf-8"
, dataType: "json"
, success: function(msg) {
alert("Success : " + msg.d);
}
, error: function(error) {
$("#lblSample").text(error.status);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="lblSample"></asp:Label>
<input type="button" id="btnSample" runat="server" value="Show What" />
</form>
</body>
</html>
That's a copy and paste. I've tested it in IE8 and it works fine.
The one change I did make was changing your success output to use msg.d This is so it outputs Success : jQuery is Super. msg would NOT cause a crash - it would just output Success : [object Object] (msg is a object that contains a string called d which the return from the static method is called).
I haven't changed your static method at all
This is in my class (remember Default.aspx)
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string SampleMethod()
{
return "jQuery is Super";
}
}
This is sitting inside my Default.aspx.cs file
I tried messing around to get a 200 OK error and the ONLY time I managed this was when I had
, contentType: "application/ json;charset=utf-8"
That has a space between the / and json.
But that isn't in your question. Maybe it is sitting in your code that way and you fixed it in the question?
One thing I see different about your script than the way I use it is wrapping the {} in the data part with quotes.
Try this:
, data: "{}"
Also,
This is a good article with some jquery ajax caveats:
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Your button is posting back instead of calling the click event. To stop the unintentional postback add e.preventDefault to your click handler. I'd also suggest not using a server side control (ie removing the runat=server) unless absolutely necessary. It just adds unneeded overhead.
I have the same problem too, but when i copy and paste the code into a new project it works fine. I think there should be something wrong with web.config
I've seen lots of related questions, but nowhere have I found a simple example of code that passes parameters back to a page method via jquery.
I've looked through some of the examples at encosia.com (thanks, Dave) but still haven't managed to get it working. Here's the code so far:
Updated - added some code to pass in params, but it's still not working.
test.aspx:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>test page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
var intxt = document.getElementById("<%= txtIn.ClientID %>").value;
var params = $.toJSON({ 'inStr': intxt });
$.ajax({
type: "POST",
url: "test.aspx/RunTest",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="Result">Click here</div>
<asp:TextBox ID="txtIn" runat="server"></asp:TextBox>
</form>
</body>
</html>
and in test.aspx.vb:
<WebMethod()> _
Public Shared Function RunTest(ByVal instr As String) As String
Return "this is your string: " + instr
End Function
Update:
The RunTest menthod above is never called. However, if I also have:
<WebMethod()> _
Public Shared Function RunTest() As String
Return "no params here"
End Function
Then the 2nd method IS called.
What am I missing? Is this the wrong approach?
The parameters are case sensitive. Your
var params = $.toJSON({ 'inStr': intxt });
Doesn't match the method signature:
Public Shared Function RunTest(ByVal instr As String) As String
The rest of it looks correct.
I would generally suggest using json2.js' JSON.stringify() to serialize JSON on the client-side, instead of other plugins like $.toJSON. json2.js' API matches the ECMA standard for browser-native JSON support which newer browsers are implementing (IE8 and Fx3.5 so far). So, if you're using JSON.stringify() to serialize your objects, it will automatically upgrade to the faster, native functionality in those browsers.
See https://stackoverflow.com/questions/570962/jquery-ajax-form-submitting
You need to load the textbox by ClientID.
I need to set a single property in a jQuery command using a value that is calculated in the code-behind. My initial thought was to just use <%= %> to access it like this:
.aspx
<script type="text/javascript" language="javascript">
$('.sparklines').sparkline('html', {
fillColor: 'transparent',
normalRangeMin: '0',
normalRangeMax: <%= NormalRangeMax() %>
});
</script>
.aspx.cs
protected string NormalRangeMax() {
// Calculate the value.
}
It smells odd to have to call from the ASPX page to just get a single value though. Not to mention I have an entire method that does a small calculation just to populate a single property.
One alternative would be to create the entire <script> block in the code-behind using clientScriptManager.RegisterClientScriptBlock. But I really don't like putting entire chunks of JavaScript in the code-behind since its, well, JavaScript.
Maybe if I end up having many of these methods I can just put then in a partial class so at least they are physically separate from the rest of the code.
What method would you recommend as being easy to understand and easy to maintain?
The <% %> works fine. One thing that I do is set a value in a hidden field on the page (then writing the necessary javascript to extract that value), this is nice because I can change that hidden field via javascript and when/if the page posts back I can get that new value from code behind as well.
If you need to call the method on demand, you could do an jQuery AJAX call to a ASP.NET WebMethod to grab the data and re-populate the various options. You can find a good tutorial on how to do that here: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Below is some sample code using the hidden field method (using the datepicker control, but you'll get the idea):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtCalendar" runat="server" />
<asp:HiddenField ID="hfTest" runat="server" />
</div>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ui.jquery.com/latest/ui/ui.datepicker.js"></script>
<script type="text/javascript">
var dateMinimum = new Date($("#<%= hfTest.ClientID %>").val());
$(function() {
$("#<%= txtCalendar.ClientID %>")
.datepicker({
minDate: dateMinimum
});
});
</script>
</body>
And the code behind Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
// Set Value of Hidden Field to the first day of the current month.
this.hfTest.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).ToString("MM/dd/yyyy");
}
Personally, I would use the <% %> method. This is what the view is for. I don't like the RegisterClientScriptBlock at all. If you ever move to MVC you will get used to the <% %> ... :)
I ran into this problem a while back. I recommend <% %> for single variable stuff. I find the RegisterClientScriptBlock function useful only if I ever need the code-behind to determine which scripts to run.
Rick has a nice article about passing server vars to client script
I would like to know some of the strategy/practice you deal with to handle unhandled exceptions in ASP.NET MVC.
In short I want to avoid the yellow screen whenever any error happens and show a error consistent error message to the visitor.
I mean do you write a controller for this which shows the appropriate error page or you go some other way like writing an httpmodule and trapping the error at a global level.
Any inputs in this direction is appreciated.
Using the HandleError attribute is the way to go. Here is a small sample which I use to handle Ajax calls from JQuery, ExtJs, and others.
On your controller
public class DataController : Controller
{
[HandleError(ExceptionType = typeof(ArgumentException), View = "ErrorAjax")]
public void Foo(string x, string y)
{
if (String.IsNullorEmpty(x))
throw new ArgumentException("String cannot be empty!");
// Call your layers or whatever here
AnotherCall();
}
}
Then on your view (ErrorAjax). Notice it's strongly typed (HandleErrorInfo)
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HandleErrorInfo>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Sorry Dude!</title>
</head>
<body>
<div>
<!-- be creative here-->
Sorry, an error occurred while processing your request.
Action = <%= ViewData.Model.ActionName %>
Controller = <%= ViewData.Model.ControllerName %>
Message = <%= ViewData.Model.Exception.Message %>
</div>
</body>
</html>
A couple of gotchas
Check your web.config and make sure customErrors mode="On"
For starters, create the View under the Shared folder
Try the HandleError attribute.
Don't use the exception handling article that you linked to. It's an old article where they didn't have the HandleError attribute added in the framework. Use the HandleError attribute. It was added in preview 4.