Skip to main content
 首页 » 编程设计

c#之从 WebMethod 返回要在 jQuery 中使用的多个值

2024年01月13日2898°冷暖

我有 jquery 使用 ajax/json 获取元素 ID,然后点击:

[System.Web.Services.WebMethod] 
public static string EditPage(string nodeID) 
{ 
    DataTable dt = new DataTable(); 
    using (SqlConnection con = new SqlConnection(Global.conString)) 
    using (SqlCommand cmd = new SqlCommand("contentPageGetDetail", con)) 
    { 
        cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = Global.SafeSqlLiteral(nodeID, 1); 
        cmd.CommandType = CommandType.StoredProcedure; 
        cmd.ExecuteNonQuery(); 
        using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
        { 
            da.Fill(dt); 
        } 
    } 
    if (dt.Count > 0) 
    { 
      string pageTitle = dt.Rows[0]["Title"].toString(); 
      string contentID = dt.Rows[0]["ContentID"].toString(); 
      return pageTitle, contentID, nodeID; 
    } 
    else 
    { 
      return "Failed"; 
    } 
} 

当需要返回时,我想将从存储过程返回的所有内容抓取回成功部分中的 jquery 方法,并在文本字段中设置隐藏字段、下拉值和标题。

在 jQuery 中,我尝试使用“pageTitle”,但它未定义。在显示表单之前,我需要在 jQuery 端执行哪些操作才能获取返回的内容并填充我的 Web 表单中的字段?

请您参考如下方法:

您需要创建一个结构或类来返回:

public struct TheStruct  
{  
    public string pageTitle;  
    public int contentID,  
    public int nodeID;  
} 
 
[System.Web.Services.WebMethod] 
public static TheStruct EditPage(string nodeID) 
{ 
    <your code here> 
 
    var result = new TheStruct(); 
    result.pageTitle = "Test"; 
    result.contentID = 1; 
    return result; 
} 

如果你通过了:

 contentType: "application/json; charset=utf-8", 

在 AJAX 调用中,您将获得一个 JSON 回复,您可以像这样解析它:

var obj = jQuery.parseJSON(webserviceReply); 
alert(obj.pageTitle);