2015-12-03 3 views
1

JQuery/Javascript: Хотите вызвать updateNotification() Fuction после уведомления__сочетания_изменения и вернуть false. веб-метод находится на главной странице.Как вызвать веб-метод главной страницы?

<script type="text/javascript" > 
    $(document).ready(function() { 
     $("#notificationLink").click(function() { 
      $("#notificationContainer").fadeToggle(300); 
      $("#notification_count_span").fadeOut("slow"); 
      return false; 
      // updateNotification() 
     }); 

     //Document Click 
     $(document).click(function() { 
      $("#notificationContainer").hide(); 
     }); 
    }); 
    function updateNotification() { 
     $.ajax({ 
      type: "POST", 
      url: "SiteMaster.master/UpdateNotification", 
      data: '{nForId: "' + $("#<%=sessionUnameHf.ClientID%>")[0].value + '" }', 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (msg) { 
       //alert(msg.d) 
       //do nothing 
      } 
     }); 
    } 
</script> 

HTML Html код в главной странице.

<asp:Label ID="notification_count_lbl" runat="server" Text=""></asp:Label></span> 
      <asp:LinkButton ID="notificationLink" runat="server">Notifications</asp:LinkButton> 
<!--<a href="#" id="notificationLink1" runat="server" onclick="updateNotification()">Notifications</a>--> 
<div id="notificationContainer"> 
<div id="notificationTitle">Notifications</div> 
<div id="notificationsBody" class="Repeater"> 
    <asp:Repeater ID="Repeater1" runat="server" EnableViewState="true" onitemcommand="view">   
<ItemTemplate > 
    <p> 
<tr> 
<td><asp:Label ID="Label1" runat="server" CssClass="trHeader" Text='<%#Eval("NotificationTitle")%>'/></td> 
    </tr></p><p><br /> 
<tr class="trMessage"> 
<td> 
    <asp:LinkButton ID="nDescLbl" runat="server" CommandName="viewCase" Text='<%#Eval("NotificationDescription")%>' CssClass="trMessage"></asp:LinkButton> 
    <asp:Label ID="Label2" runat="server" Text='<%#Eval("NotificationID")%>'></asp:Label> 
    <asp:HiddenField ID="nIdHf" runat="server" Value='<%#Eval("NotificationID")%>'/> 
</td> 
    </tr></p><p><br /> 
<tr class="trFooter"> 
<td> 
    <asp:Label ID="Label3" runat="server" CssClass="trFooter" Text='<%#Eval("NotificationDate")%>'/></td> 
    </tr></p> 
    <br /> 
    <hr style="color:darkgray;"/> 
    </ItemTemplate> 
    </asp:Repeater> 
</div> 
<div id="notificationFooter"><a href="Home.aspx" style="color:#006699;">See All</a></div> 
</div> 

WebMethod WebMethod в главной странице.

[System.Web.Services.WebMethod] 
public static string UpdateNotification(string nForId) 
{ 
    string returnValue = string.Empty; 
    try 
    { 
     using (SqlConnection connection = ConnectionManager.GetDatabaseConnection()) 
     { 
      SqlCommand cmd = new SqlCommand("UpdateNotification", connection); 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.AddWithValue("@nForId", nForId); 
      returnValue = cmd.ExecuteScalar().ToString(); 
      connection.Close(); 
     } 
    } 
    catch 
    { 
     returnValue = "error"; 
    } 
    return returnValue; 
} 
+0

Так что это вопрос? Вы получаете какое-либо исключение? –

+0

Вы не можете вызвать веб-метод с главной страницы. – Mairaj

+0

Как вызвать уведомление об обновлении() после того, как notification_count_span исчезнет? – Deepak

ответ

1

Это не представляется возможным из-за MasterPages быть ресурсом на стороне сервера, которые не будут обслуживаться IIS, который в настоящее время ссылаются в вашем $.ajax вызова.

Если вам требуется, чтобы несколько страниц контента имели доступ к WebMethod, переместите свой код на веб-службу (ASMX).

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService] 
public class SiteService: System.Web.Services.WebService 
{ 
    [WebMethod] 
    public static string UpdateNotification(string nForId) 
    { 
     string returnValue = string.Empty; 
     try 
     { 
      using (SqlConnection connection = ConnectionManager.GetDatabaseConnection()) 
      { 
       SqlCommand cmd = new SqlCommand("UpdateNotification", connection); 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.Parameters.AddWithValue("@nForId", nForId); 
       returnValue = cmd.ExecuteScalar().ToString(); 
       connection.Close(); 
      } 
     } 
     catch 
     { 
      returnValue = "error"; 
     } 
     return returnValue; 
    } 
} 
$.ajax({ 
    type: "POST", 
    url: "SiteService.asmx/UpdateNotification", 
    ... 

Если единственной целью #notificationLink является для вызова JavaScript, то вы можете избавиться от серверного элемента управления.

<a id="notificationLink">Notifications</a> 
$("#notificationLink").click(function (e) { 
    e.preventDefault(); 
    $("#notificationContainer").fadeToggle(300); 
    $("#notification_count_span").fadeOut("slow"); 
    updateNotification(); 
}); 

Подробнее: event.preventDefault()

+0

Вместо этого мы могли бы использовать Web-API для определения метода на стороне сервера и использовать этот метод для сценария на стороне клиента. Было бы проще, но нужно внести некоторые дополнительные изменения кода, такие как настройка маршрута в Global.asax .cs файл. Ссылка: http://www.webdevelopmenthelp.net/2014/05/using-web-api-with-web-forms.html – Karan

+0

код для вызова updateNotification() в ("#notificationLink"). щелкните (function() – Deepak

+0

@Goran, не ссылаясь на updateNotification(). – Deepak

Смежные вопросы