Using partials in Web Forms

time to read 2 min | 235 words

Partial is a MonoRail term to a piece of UI that you extract outside, so you can call it again, often with Ajax. This is something that is harder to do in WebForms. Yesterday I found an elegant solution to the problem.

ASPX code:

<div id="UserDetailsDiv">
   <ayende:UserDetails runt="server" ID="TheUserDetails"/>

User Control:

Name: <asp:label ID="Name" runat="server"/> <br/>
Email: <asp:label ID="Email" runat="server"/> 

Client Side Code:

function changeUser(newUserId, div)
	var srv = new MyApp.Services.UserDetails();
	srv.GetUserDetailsView(newUserId, onSucccessGetUserDetailsView, null, div);

function onSucccessGetUserDetailsView(response, userContext)
	var div = $(userContext);
	div.innerHTML = response;
	new Effect.Highlight(div);

Web Service Code:

[WebMethod(EnableSession = true)]
public string GetUserDetailsView(int userId)
	User user = Controller.GetUser(userId);
	//there may be a better way to do this, I haven't bothered looking
	UserDetails userDetails = (UserDetails)new Page().LoadControl("~/Users/UserControls/UserDetails.ascx");
	userDetails.User = user;
	using(StringWriter sw = new StringWriter())
	using(HtmlTextWriter ht = new HtmlTextWriter(sw))
		return sw.GetStringBuilder().ToSTring();