Bạn sẽ chạy vào một loạt các vấn đề: ViewState, điều khiển cần thẻ biểu mẫu, postbacks sẽ không hoạt động nhưng nếu bạn đang làm điều này với một điều khiển hoàn toàn là View
nó sẽ hoạt động tốt.
Script:
//use .ready() or pageLoad() and pass params etc if you need to
$.ajax({
type: 'POST',
url: 'Default.aspx/GetControlViaAjax',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#yourdiv').html(data.d);
}
});
WebMethod:
[WebMethod]
public static string GetControlViaAjax()
{
//example public properties, send null if you don't have any
Dictionary<string, object> d = new Dictionary<string, object>();
d.Add("CssClass", "YourCSSClass");
d.Add("Title", "Your title");
return RenderUserControl("/yourcontrol.ascx", true, d, null, null);
//use this one if your controls are compiled into a .dll
//return RenderUserControl(null, true, d, "Com.YourNameSpace.UI", "AwesomeControl");
}
Render phương pháp:
private static string RenderUserControl(string path, bool useFormLess,
Dictionary<string, object> controlParams, string assemblyName, string controlName)
{
Page pageHolder = null;
if (useFormLess)
{
pageHolder = new FormlessPage() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath }; //needed to resolve "~/"
}
else
{
pageHolder = new Page() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath };
}
UserControl viewControl = null;
//use path by default
if(String.IsNullOrEmpty(path))
{
//load assembly and usercontrol when .ascx is compiled into a .dll
string controlAssemblyName = string.Format("{0}.{1},{0}", assemblyName, controlName);
Type type = Type.GetType(controlAssemblyName);
viewControl = (UserControl)pageHolder.LoadControl(type, null);
}
else
{
viewControl = (UserControl)pageHolder.LoadControl(path);
}
viewControl.EnableViewState = false;
if (controlParams != null && controlParams.Count > 0)
{
foreach (var pair in controlParams)
{
Type viewControlType = viewControl.GetType();
PropertyInfo property =
viewControlType.GetProperty(pair.Key);
if (property != null)
{
property.SetValue(viewControl, pair.Value, null);
}
else
{
throw new Exception(string.Format(
"UserControl: {0} does not have a public {1} property.",
path, pair.Key));
}
}
}
if (useFormLess)
{
pageHolder.Controls.Add(viewControl);
}
else
{
HtmlForm form = new HtmlForm();
form.Controls.Add(viewControl);
pageHolder.Controls.Add(form);
}
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
}
FormlessPage lớp:
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
Vui lòng xem các liên kết hữu ích này để giải quyết vấn đề: - ["Phương pháp không đồng bộ và điều khiển người dùng"] (http://forums.asp.net/t/1468026.aspx/1) - ["ASP .NET - Asynchronous User Control "] (http://rsuharta.wordpress.com/2011/04/27/asp-net-asynchronous-user-control/) –