[ASP.NET MVC] Combining Multiple Partial Views Together

By
Advertisement

------------------------Class------------------------------
public class MultipleViewResult : ActionResult
{
    public const string ChunkSeparator = "---|||---";
    public IList<PartialViewResult> PartialViewResults { get; private set; }
    public MultipleViewResult(params PartialViewResult[] views)
    {
        if (PartialViewResults == null)
            PartialViewResults = new List<PartialViewResult>();
        foreach(var v in views)
            PartialViewResults.Add(v);
    }
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");
        var total = PartialViewResults.Count;
        for (var index = 0; index < total; index++)
        {
            var pv = PartialViewResults[index];
            pv.ExecuteResult(context);
            if (index < total - 1)
                context.HttpContext.Response.Output.Write(ChunkSeparator);
        }
    }
}
------------------------Controler ------------------------------

public ActionResult Customers()

{
    var customers = _repository.FindAll();
    // Combine multiple partial views
    var model = new IndexViewModel(customers);
    return new MultipleViewResult(
        PartialView(Common.Views.ListOfCustomers, model),
        PartialView(Common.Views.OnBehalfOfCustomers, model));
}
------------------------Using with AJAX------------------------------
function d(id) {
    var url = "/home/d/";
    $.post(url, { id: id })
     .done(function (response) {
        var chunkSeparator = "---|||---";
        var chunks = response.split(chunkSeparator);
        $("#listOfCustomers").html(chunks[0]);
        $("#onBehalfMenu").html(chunks[1]);
    });
}

0 blogger:

Đăng nhận xét