2017-04-07 89 views
0

When i'm trying to assign value in textbox through webmethod on my page i got this exception獲取異常屬性

我的HTML代碼

<form id="form1" runat="server"><br /><br /> 
<asp:ScriptManager ID="src" runat="server" EnablePageMethods="true"></asp:ScriptManager> 
<asp:UpdatePanel ID="up1" runat="server"> 
    <ContentTemplate>   
     <div class="row"> 
      <div class="col-md-6"> 
       <asp:Button ID="btnChangeMake" runat="server" Text="Change Make" OnClientClick="ChangeMake()"/><br /> 
       <asp:TextBox ID="txtMake" runat="server"></asp:TextBox> 
      </div> 
     </div> 
    </ContentTemplate> 
</asp:UpdatePanel> 

JavaScript代碼

function ChangeMake() { 
PageMethods.ChangeMakeText("Devil", onSucess, onError); 
function onSucess(result) { 
    alert(result); 
} 
function onError(result) { 
    alert(result); 
} 

}

C#代碼

[WebMethod] 
public static void ChangeMakeText(string DataValue) 
{ 
    if (HttpContext.Current != null) 
    { 
     Page page = (Page)HttpContext.Current.Handler; 
     TextBox txtMake = (TextBox)page.FindControl("txtMake"); 
     txtMake.Text = DataValue; 
    } 
} 

'txtMake.Text = DataValue;'的異常

類型「System.NullReferenceException」的一個例外發生在App_Web_0lr1r3rs.dll但在用戶代碼中沒有處理

其他信息:對象沒有設置爲一個對象的一個​​實例。

+0

Web方法,我不認爲你可以做這樣的 –

+0

我如何從JavaScript調用C#方法... – Nishant

+0

您無法訪問控件的Web方法,而你可以發送回值在JavaScript中調用方法並將其分配給txtMake – Adil

回答

0

您無法訪問web方法中的頁面控件,您可以將值發送回javascript中的調用方法並將其分配給txtMake。

C#代碼

public static string ChangeMakeText(string DataValue) 
{ 
    //Your code  
    return DataValue; 
} 

JavaScript代碼

function ChangeMake() { 
    PageMethods.ChangeMakeText("Devil", onSucess, onError); 
    function onSucess(result) { 
      document.getElementById("<%=txtMake.ClientID%>").value = result; 
    } 
} 

您已經使用Ajax和按鈕btnChangeMake UpdatePanel這樣綁定click事件(通過雙擊它在desginer),並更改服務器端的價值點擊處理器。

void btnChangeMake_Click(Object sender, EventArgs e) 
{ 
    txtMake.Text = DataValue; 
}