调用代码从JavaScript功能的背后(而不是AJAX!)
我有我的服务器端的功能。
I have a function on my server side.
protected void SelectParticipant(string CompanyId, string EmployeeNumber)
{
//I do some stuff here.
}
我想从JavaScript调用该函数在客户端上。我试图寻找它,但我发现建议是调用通过AJAX页面方法。我不想说,我要进行回传。
I want to call this function from JavaScript on the client side. I've tried searching for it, but all the suggestions I found were for calling a Page Method via AJAX. I don't want that, I want to cause a postback.
function MyJSFunction(companyid, employeenumber)
{
//cause postback and pass the companyid and employee number
//this is where I need help!
}
我怎么能进行回传,并从我的JavaScript运行服务器端的功能?
How can I cause a postback and run a server side function from my JavaScript?
下面是我做到了......
Here's how I did it...
<script type="text/javascript">
function AddParticipant(companyid, employeenumber)
{
$("#AddParticipantPanel").dialog("close");
var myargs = {CompanyId: companyid, EmployeeNumber: employeenumber};
var myargs_json = JSON.stringify(myargs);
__doPostBack('<%= SelectParticipantBtn.UniqueID %>', myargs_json);
}
</script>
<asp:Button runat="server" ID="SelectParticipantBtn" ClientIDMode="Static" OnClick="SelectParticipantBtn_Click" style="display:none;" />
和服务器端...
/* this is an inner class */
public class SelectParticipantEventArgs
{
public string CompanyId {get; set;}
public string EmployeeNumber {get; set;}
}
protected void SelectParticipantBtn_Click(object sender, EventArgs e)
{
string args = Request.Form["__EVENTARGUMENT"];
var myargs = JsonConvert.DeserializeObject<SelectParticipantEventArgs>(args);
string emp_no = myargs.EmployeeNumber;
string company_id = myargs.CompanyId;
//do stuff with my arguments
}
而不是使用HiddenFields的,我用了隐藏式按键。这种模式效果更好,因为我可以直接到该按钮的事件处理程序,而不必添加代码到Page_Load功能。
Instead of using HiddenFields, I used a hidden button. This model works better because I can go directly to the button's event handler instead of having to add code to the Page_Load function.