是否可以将WebMethod放在ascx.cs文件中(对于UserControl),然后从客户端jQuery代码调用它?
出于某些原因,我无法将WebMethod代码放在.asmx或.aspx文件中.
示例:在ArticleList.ascx.cs中,我有以下代码:
[WebMethod]
public static string HelloWorld()
{
return "helloWorld";
}
Run Code Online (Sandbox Code Playgroud)
在ArticleList.ascx文件中,我可以调用WebMethod,如下所示:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
{
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: "ArticleList.ascx/HelloWorld",
success: function(msg) {
alert(msg);
}
});
Run Code Online (Sandbox Code Playgroud)
而firebug的错误是:
<html>
<head>
<title>This type of page is not served.</title> …Run Code Online (Sandbox Code Playgroud) 我正在做一些简单的测试(准备一个更大的项目)来使用JQuery AJAX调用ASP.NET WebMethod.在我的示例中,我的WebMethod返回一个简单的字符串.但是,当我尝试使用JQuery调用它时,我会返回整个HTML页面内容,而不仅仅是我的字符串.我错过了什么?
客户端 :
$(document).ready(function ready() {
$("#MyButton").click(function clicked(e) {
$.post("Default.aspx/TestMethod",
{name:"Bob"},
function(msg) {
alert("Data Recieved: " + msg);
},
"html"
);
});
});
Run Code Online (Sandbox Code Playgroud)
服务器端:
using System;
using System.Web.Services;
namespace JqueryAjaxText
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestMethod(string name)
{
return "The value submitted was " + name;
}
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个ASP.NET MVC3应用程序,当用户点击我的锚标签时,我想将3个数据发送到一个动作:
<a onclick='editDescription(<#= DocID,FileName,Description #>)'></a>
Run Code Online (Sandbox Code Playgroud)
这是调用我的操作的JavaScript:
function editDescription(docId,fileName,description) {
var url = "@Url.Content("~/OrderDetail/_EditDescription/")" + docId+'/'+
fileName + '/' + description;
//do the rest}
Run Code Online (Sandbox Code Playgroud)
我的行动:
public ActionResult _EditDescription(string id,string filename, string descritpion)
Run Code Online (Sandbox Code Playgroud)
我关注的部分是FileName和Description,因为这些可以是loooooong,我不希望网址如此出现:
http://localhost/OrderDetail/_EditDescription/123/some long filename.pdf/this is a long description for the name
Run Code Online (Sandbox Code Playgroud)
如何将数据发送到我的操作而不必像查询字符串一样发送?谢谢