标签: webmethod

使用带有母版页的Web方法

我在我的站点中的所有页面上都有一个函数,它位于我的母版页中,我希望它从一些jQuery Ajax方法运行.

我现在有一些像这样的代码

jQuery的

$(document).ready(function() {
  $("#test").click(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/GetDate",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        $("#test").text(msg.d);
      }
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

主页面中的HTML

<div id="test">Click here for the time.</div>
Run Code Online (Sandbox Code Playgroud)

我的Master VB背后的Asp.Net代码

<WebMethod> _
Public Shared Function GetDate() As String
    Return DateTime.Now.ToString()
End Function
Run Code Online (Sandbox Code Playgroud)

目前,除非我将Web方法移动到Default.aspxVB页面,否则这不起作用

有没有办法可以改变这一部分

url: "Default.aspx/GetDate",
Run Code Online (Sandbox Code Playgroud)

要使用母版页功能?

我试着改成它

url: "template.master/GetDate",
Run Code Online (Sandbox Code Playgroud)

但这只是给我一个404错误

有任何想法吗?

提前致谢

asp.net ajax jquery webmethod

7
推荐指数
1
解决办法
1万
查看次数

当url重写活动时,WebMethod不会被调用

我知道那里有类似的帖子,但我发现其中任何一个都没有帮助.

我的网络方法在我不使用网址重写时工作,但是一旦打开它就停止工作.

jQuery的

        $.ajax({
            type: "POST",
            url: "index.aspx/SaveSetting",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                console.log(msg);
            }
        });
Run Code Online (Sandbox Code Playgroud)

C#

    [WebMethod()]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public static string SaveSetting()
    {
        return "OK";
    }
Run Code Online (Sandbox Code Playgroud)

当调用它时,我得到了我的页面的完整HTML,没有"OK"消息.我运行调试器,看到当我调用web方法时,它会在我的页面中触发Page_Load而不是web方法.

所以我得到了corerct路径,但没有调用web方法.

我使用C#,jQuery,ASP.NET 3.5.

有帮助吗?

c# ajax jquery webmethod

6
推荐指数
1
解决办法
3417
查看次数

通过Ajax调用通过Web方法从C#下载文件?

我试图通过webmethod从服务器下载文件,但它对我不起作用.我的代码如下

     [System.Web.Services.WebMethod()]
public static string GetServerDateTime(string msg)
{
    String result = "Result : " + DateTime.Now.ToString() + " - From Server";
    System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString()) + "\\" + "Default.aspx");
    System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
    Response.ClearContent();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.WriteFile(file.FullName);
    //HttpContext.Current.ApplicationInstance.CompleteRequest();
    Response.Flush();
    Response.End();
    return result;        
}
Run Code Online (Sandbox Code Playgroud)

我的ajax调用代码如下

    <script type="text/javascript">
    function GetDateTime() {
                    var params = "{'msg':'From Client'}";
                    $.ajax
                      ({
                          type: "POST",
                          url: "Default.aspx/GetServerDateTime",
                          data: params,
                          contentType: "application/json;charset=utf-8",
                          dataType: "json",
                          success: function (result) {
                              alert(result.d); …
Run Code Online (Sandbox Code Playgroud)

ajax webmethod

6
推荐指数
1
解决办法
3万
查看次数

ashx,asmx,axd + cs(处理程序),webmethod(在aspx中)和asp.net framework 4.5中的异步方法有什么区别?

我需要知道这些文件的技术差异.哪一个是最好的选择?何时以及为什么要使用它?我需要一个人的答案,而不是MSDN链接.

asp.net asmx ashx axd webmethod

6
推荐指数
1
解决办法
9331
查看次数

LoadControl,WebMethod中的usercontrol

我正在尝试通过WebMethod 以下方式发送电子邮件.下面是我通常在常规帖子上使用的代码

[WebMethod]
public static void SendEmail(string name, string phone, string emailaddress, string interest, string comments)
{
    var control = LoadControl("~/Shared/Controls/EmailTemplate_PartnerWithUs.ascx");

    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    Html32TextWriter htw = new Html32TextWriter(sw);

    control.RenderControl(htw);

    sb.Replace("%name%", name);
    sb.Replace("%phone%", phone);
    sb.Replace("%emailaddress%", emailaddress);
    sb.Replace("%interest%", interest);
    sb.Replace("%comments%", comments);
    EmailUtility.SendEmailMessage(SettingsManager.GetContactRecipientEmails(), "CoyleHomeBuyers.com Partner Form", sb.ToString());
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

An object reference is required for the non-static field, method, or property 'System.Web.UI.TemplateControl.LoadControl(string)'
Run Code Online (Sandbox Code Playgroud)

有没有办法在WebMethod中加载此控件?

c# asp.net user-controls webmethod

6
推荐指数
1
解决办法
2728
查看次数

$ .ajax返回页面的HTML而不是结果

我写了一个简单的web方法,我在客户端调用它来检查数据库中是否存在文本更改的值.它在本地工作正常,但是当我将它移动到我们的开发环境时,它会在响应中返回页面的整个HTML.我注意到的唯一的事情是本地Response.Server是IIS7.5,但在我们的Dev服务器上它是IIS6.

这是我的代码:

服务器代码

[ScriptMethod]
[System.Web.Services.WebMethod]
public static bool CheckInvoiceExists(string vendorNumber, string invoiceNumber)
    {
        try
        {
            return RequestEntry.CheckInvoiceExists(vendorNumber, invoiceNumber);
        }
        catch (Exception exp)
        {
            EventLogging.LogError("Error checking if invoice exists: " + exp.Message);
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

客户代码

function CheckInvoiceExists() {
//var vendNo = $('#VendNoInputDisplay').text();
var vendNo = $('#VendorNumber').val();
var invNo = $('#InvNoInput').val();
var error;
$.ajax({
    type: "POST",
    aSync: false,
    url: "PaymentRequest.aspx/CheckInvoiceExists",
    data: JSON.stringify({
        vendorNumber: vendNo,
        invoiceNumber: invNo
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        if (data.d) {
            $('#ErrorList').text(GetErrorText("invoiceNumberExists")); …
Run Code Online (Sandbox Code Playgroud)

c# asp.net ajax jquery webmethod

6
推荐指数
1
解决办法
4190
查看次数

如何将json字符串传递给webmethod c#ASP.NET

我试图将javascript对象字符串化,然后将字符串作为参数传递给Code Behind中的WebMethod.我无法让它工作,因为我得到500的内部服务器错误,堆栈跟踪说参数缺少值.

这是javascript代码:

var jSon = JSON.stringify(javascriptObject); 
// "{"Foretagsnamn":"Avector","BGFarg":"000000","TextColor":"fafafa","FooterFarg":"ffffff","FooterColor":"000000","FooterLinkColor":"050505","FeaturedBorderColor":"","HoverFarg":"12ebeb","RutFarg":"0d0d0d","SelectedRutFarg":"","RutColor":"FFFFFF","LankColor":"","DelaMedSig":"1","PersonalSida":"0","StartpageTitle":"","StartpageDescription":"","GoogleMaps":"<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://maps.google.se/maps?f=q&amp;source=embed&amp;hl=sv&amp;geocode=&amp;q=Avector AB&amp;aq=&amp;sll=56.225986,12.870827&amp;sspn=0.076248,0.154324&amp;ie=UTF8&amp;hq=Avector AB&amp;hnear=&amp;t=m&amp;cid=645910733081021950&amp;iwloc=A&amp;ll=56.224594,12.859229&amp;spn=0,0&amp;output=embed\"></iframe><br /><small><a href=\"https://maps.google.se/maps?f=q&amp;source=embed&amp;hl=sv&amp;geocode=&amp;q=Avector AB&amp;aq=&amp;sll=56.225986,12.870827&amp;sspn=0.076248,0.154324&amp;ie=UTF8&amp;hq=Avector AB&amp;hnear=&amp;t=m&amp;cid=645910733081021950&amp;iwloc=A&amp;ll=56.224594,12.859229&amp;spn=0,0\" style=\"text-align:left\">Visa större karta</a></small>","HittaKartaUrl":"http://www.hitta.se/avector ab/ängelholm/hxTP-4v1HG?vad=Avector AB","EniroKartaUrl":"http://kartor.eniro.se/m/aKkhi","Ikoner":"2","Email":"info@avector.com","AdressSida":"1","shadowColor":"ffffff","lineColor":"2b292b","MenuHoverIcon":"Välj bild från server","fontFamily":"Verdana","supportText":"Support Avector","captcha":true,"metaKeywords":"","ShowSupportInFooter":true}"

$.ajax({
    type: "POST",
    url: "Post/Installningar.aspx/Updatera",
    data: jSon,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {

        var resultAsString = result.d;
        //_this.parent().siblings('.SavedStatus').html(resultAsString);

        if (resultAsString == "1") { // Gick bra att spara.
           alert("Uppgifterna är sparade.");
           document.location = document.location;
        }
        else {
           $('#StatusText').html("Gick inte att spara uppgifterna.");
        }


    },
    error: function …
Run Code Online (Sandbox Code Playgroud)

javascript asp.net ajax jquery webmethod

6
推荐指数
1
解决办法
1万
查看次数

使用$ .ajax调用Web方法时,身份验证失败错误

当我进行JQuery调用时,我收到一个身份验证失败的响应:

{
    Message: "Authentication failed.", 
    StackTrace: null, 
    ExceptionType: "System.InvalidOperationException"
}
Run Code Online (Sandbox Code Playgroud)

jQuery调用:

$(document).ready(function () {
    //Handle the change event for the drop down list
    $("#ddRegions").change(function () {
        //create the ajax request
        $.ajax({
            type: "POST", //HTTP method
            url: '<%= ResolveUrl("WebForm2.aspx/getLocations")%>', //page/method name
            data: "{}", //json to represent argument
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) { //handle the callback to handle response                
                //request was successful. so Retrieve the values in the response.
                alert(msg.toSource());
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

网络方法:

public static string …
Run Code Online (Sandbox Code Playgroud)

c# asp.net ajax jquery webmethod

6
推荐指数
1
解决办法
8556
查看次数

Ajax数据源(对象):TypeError:f未定义

我正在开发我的ASP.Net Web应用程序,我必须使用Ajax数据源填充HTML表,我正在使用jQuery DataTables插件.

HTML代码:

<table class="table table-striped table-hover table-bordered display" id="example" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Prctice Group Risk No
            </th>
            <th>Practice_Group
            </th>
            <th>Risk_Category
            </th>
        </tr>
    </thead>
</table>
Run Code Online (Sandbox Code Playgroud)

JavaScript代码:

$('#example').DataTable({
    "ajax": {
        "dataType": 'json',
        "contentType": "application/json; charset=utf-8",
        "type": "POST",
        "url":"index.aspx/Risky"
    },
    "columns": [
        { "data": "Prctice_Group_Risk_No" },
        { "data": "Practice_Group" },
        { "data": "Risk_Category" }]
});
Run Code Online (Sandbox Code Playgroud)

这是我的Web方法我正在调用获取对象列表的JSON响应

 [WebMethod]
 [ScriptMethod]
    public static string Risky()
    {
        return JsonConvert.SerializeObject(riskList);
    }
Run Code Online (Sandbox Code Playgroud)

来自服务器的JSON响应:

d:"[{"Prctice_Group_Risk_No":1,"Practice_Group":"M&A","Risk_Category":"Conflicts of Interests"},{"Prctice_Group_Risk_No":2,"Practice_Group":"abc","Risk_Category":"Client Care and Communication"}]
Run Code Online (Sandbox Code Playgroud)

Jquery DataTables官方网站http://www.datatables.net/examples/ajax/objects.html中描述的JSON响应对我来说似乎很好 .

但是表中没有填充任何数据,我在Firebug控制台中收到以下错误

TypeError:f未定义

asp.net jquery json datatables webmethod

6
推荐指数
1
解决办法
1万
查看次数

Shared方法中的HttpContext.Current.Session不会持久更改

我在System.Web.UI.Page中使用一些WebMethod来处理一些ajax请求,我试图在会话中存储一个对象,以便在几个ajax请求之后保留信息,甚至在离开页面并返回之后.

我正在访问会话HttpContext.Current.Session("foo"),如果它没什么,我通过它设置它HttpContext.Current.Session("foo") = New Bar().

我遇到的问题是,在设置之后,下次我按下该方法时它已被重置.我尝试更改在其他地方设置的其他会话变量,它们也会被还原.这告诉我,我正在获取会话状态的副本,而不是我可以更新并导致从请求到请求持久化的引用.我仔细检查EnableSession了WebMethod 的属性是否为True,但仍未保留更改为会话状态.

方法声明:

<System.Web.Services.WebMethod(EnableSession:=True)>
Public Shared Function foo(ByVal woNum As String, ByVal workCenter as String) As ToolingModel
    Return ToolingModel.getSessionTooling(woNum, workCenter)
End Function
Run Code Online (Sandbox Code Playgroud)

getSessionTooling:

Public Shared Function getSessionTooling(woNum As String, workCenter As String) As ToolingModel
    Dim tooling As ToolingModel = HttpContext.Current.Session(TOOLING_MODEL_SESSION_KEY)

    If tooling Is Nothing Then
        tooling = New ToolingModel(woNum, workCenter)
        HttpContext.Current.Session(TOOLING_MODEL_SESSION_KEY) = tooling
    ElseIf tooling.woNum <> woNum OrElse tooling.workCenter <> workCenter Then
        tooling.woNum = woNum
        tooling.workCenter = workCenter
        tooling.assets.Clear() …
Run Code Online (Sandbox Code Playgroud)

vb.net session-state webmethod

6
推荐指数
1
解决办法
721
查看次数