ASP.NET WebForms PostBack 模式下 MVC 架構在 Ajax 回呼時失效:回呼返回資料需客戶端 JS 解析更新 DOM,或伺服端手工拼 HTML,導致代碼混亂、門檻高。
// 封裝 XMLHttpRequest
function Updater(ajaxTemplate, output, params, onComplete) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "Ajax.aspx", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (output) document.getElementById(output).innerHTML = xhr.responseText;
if (onComplete) onComplete(xhr.responseText);
}
};
xhr.send(params);
}
// 序列化 // Ajax.aspx.cs
protected void Page_Load(object sender, EventArgs e) {
string template = Request["ajaxTemplate"]; // 如 "Controls/UserInfo.ascx"
if (!string.IsNullOrEmpty(template)) {
Control uc = LoadControl(template);
// 可選:注入參數至 UserControl 公共屬性
Page.Controls.Add(uc);
StringWriter sw = new StringWriter();
HttpContext.Current.Server.Execute(uc, sw, true);
Response.Write(sw.ToString());
}
}