The answer is correct but. After using it for a while I came across a case when the response is split in many parts so that html is incorrect
Part 1:
<html>.....<labe
Part 2:
l/>...</html>
Also partial renders may make unexpected cases. Their html is out of the main stream too. So my solution is to do it in the Flush method after all streaming is done.
/// <summary>
/// Insert messages and script to display on client when a partial view is returned
/// </summary>
private class ResponseFilter : MemoryStream
{
private readonly Stream _response;
private readonly IList<object> _detachMessages;
public override void Flush()
{
// add messages and remove
// filter is called for a number of methods on one page (BeginForm, RenderPartial...)
// so that we don't need to add it more than once
var html = MessageAndScript(_detachMessages);
var buffer = Encoding.UTF8.GetBytes(html);
_detachMessages.Clear();
_response.Write(buffer, 0, buffer.Length);
base.Flush();
}
public ResponseFilter(Stream response, IList<object> detachMessages)
{
_response = response;
_detachMessages = detachMessages;
}
public override void Write(byte[] buffer, int offset, int count)
{
_response.Write(buffer, offset, buffer.Length);
}
private static string MessageAndScript(IList<object> detachMessages)
{
if (detachMessages.Count == 0)
return null;
var javascript = CustomJavaScriptSerializer.Instance.Serialize(detachMessages);
return "$(function(){var messages = " + javascript + @";
// display messages
base.ajaxHelper.displayMessages(messages);
})";
}
}
请发表评论