Thursday, January 17, 2013

Using MVP Pattern in ASP.NET WebForm Application

MVP - Model / View / Presenter pattern.

There are a lot of various explanations about this pattern on internet spaces and I would like to skip explain about one more time, but I would like to show 2 simple examples of MVP pattern:

1. View referred to Presenter (getting all necessary data and run presenter methods according to events)
     (See Pic 1)

2. Presenter has reference to View and initiated all view's objects and View refer back to Presenter with events fired that Presenter registered on. (See Pic 2)




Lets see which components we need to prepare for scenario Pic 1:

Lets start with Presenter Interface:

namespace Contracts
{
    public interface IMyView<T>
    {
        List<T> Model { getset; }
    }
}



... And its Concrete, our Presenter:

public class MyPresenter
{
    private IMyView<ViewModel> View { getset; }
 
    public MyPresenter(IMyView<Model> view)
    {
        View = view;
    }
 
    public void InitViewList(string categoryId = null)
    {
        var List = ServiceAgend or DALAgend or .....
  
        View.Model = (from c in List select new ViewModel
                          {
                              Name= c.Name,
                              Surname = c.SurName
                          }).ToList();
    }
}

ViewModel:

namespace ViewModels
{
    public class ViewModel
    {
        public string Name{ getset; }
        public string SurName { getset; }
    }
}


...and View code behind:

 
namespace International
{
    public partial class MyView: IMyView<ViewModel>
    {
        public static readonly string Title = "Most Popular Discounts";
        public static readonly string Footer = "See all Discounts";
        public List<ViewModel> Model { getset; }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            var presenter = new MyPresenter(this);
            presenter.InitViewList(CategoryId);
        }
    }
}



...and Sample of View.ascx


<% foreach (var item in Model)
       {%>    
         <li class="dots">
            <a href="#"><%=item.Name%></a>
            <span class="discount"><%=item.SurName%></span>
            <div class="clr"></div>
        </li>
    <% } %>




Unit Testing tip:

How to simulate HttpContextBase:


public HttpContextBase MockContext(bool isAuthenticated = falsestring username = "")
{
    //Creating the HttpContext object
    var httpContext = MockRepository.GenerateMock<HttpContextBase>();            
    //Creating the Identity object 
    var identity = MockRepository.GenerateMock<IIdentity>();
    identity.Stub(u => u.Name).Return(username);
    identity.Stub(i => i.IsAuthenticated).Return(isAuthenticated);
    //Creating the User Object 
    var user = MockRepository.GenerateMock<IPrincipal>();
    user.Stub(u => u.Identity).Return(identity);
    httpContext.Stub(ctx => ctx.User).Return(user);
    return httpContext;
}






No comments:

Post a Comment