[英]How to call in Web Forms code behind C# method from .aspx page javascript
[英]C# return linq result as a list from a wcf service method then use it in aspx web forms page
我是C#的新手,我正在嘗試使用wcf服務應用程序,該應用程序引用數據實體模型從表中選擇行。因此我找到了一種方法來返回linq查詢結果作為列表,盡管我沒有在aspx Web表單頁面中找到了一種尚未使用列表的方法。我不知道如何在aspx頁面中加載列表,到目前為止,我對msdn的研究並沒有幫助我。 我試圖以最好的方式來表達我的問題,以便您理解,這是我的代碼:
wcf服務應用程序代碼:
public List<string> getAccountInfo(int uid)
{
List<string> result = new List<string>();
try
{
using (paragon_db_Models.user_accounts_Model context = new paragon_db_Models.user_accounts_Model())
{
var query = from uacc in context.user_accounts
where uacc.user_account_id == uid
select uacc;
foreach (var c in query)
{
string row = c.user_account_id + ";" + c.order_id + ";" + c.order_state + ";" + c.estimated_cost + ";" + c.instance_form + ";" + c.time_scedule + ";" + c.invoice + ";" + c.notification + ";" + c.user_account_type + ";" + c.username + ";" + c.password;
result.Add(row);
}
}
return result;
}
catch (Exception)
{
return result;
}
}
aspx.cs代碼
protected void Page_Load(object sender, EventArgs e)
{
accountInfo_Ref.IaccountInfoSrvcClient accInfoClient = new accountInfo_Ref.IaccountInfoSrvcClient();
int id = (int)Session["UserId"];
List<string> columns = new List<string>(accInfoClient.getAccountInfo(id));
id_lbl.Text = columns[0];
order_id_lbl.Text = columns[1];
}
該服務工作正常。 我也歡迎提出更好的方法的建議。
該方法返回一個List<string>
。您只需將其存儲在List<string>
的實例中。 您必須這樣做:
List<string> columns = accInfoClient.getAccountInfo(id);
如您在評論中所說,它正在返回一個數組:
string[] columns = accInfoClient.getAccountInfo(id);
或使用隱式變量:
var columns = accInfoClient.getAccountInfo(id);
如果我正確理解了您的問題,只需這樣寫
List<string> columns = accInfoClient.getAccountInfo(id).ToList<string>();
您將獲得充滿數據的列表。
或者你無法從你的服務返回字符串,你可以返回對象的列表。
如果必須返回字符串,則必須使用String.Split方法拆分序列化的數據,但這實際上是一種較差的方法。 如果必須返回字符串,則至少可以使用更好的序列化策略,例如JSON或XML。
但請真正考慮更改您的服務界面。
現在讓我們回到使用結果:
碼:
protected void Page_Load(object sender, EventArgs e)
{
accountInfo_Ref.IaccountInfoSrvcClient accInfoClient = new accountInfo_Ref.IaccountInfoSrvcClient();
int id = (int)Session["UserId"];
List<string> rows = new List<string>(accInfoClient.getAccountInfo(id));
// display the first row
string row = rows.FirstOrDefault();
if (String.IsNullOrEmpty(row))
{
// record cannot be found
}
else
{
string[] details = row.Split(';');
id_lbl.Text = details[0];
order_id_lbl.Text = details[1];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.