Having got Razor views working in SharePoint, I needed a better way to use them - displaying the view is three lines of fairly clean code, but it’s surrounded by the all the event handler methods you need in a web forms page or control.

It turns out that with the right code in the base class, a web part can look a lot like an ASP.NET MVC controller.

public class ExampleWebPart : MvcWebPart
{
    protected override ActionResult Get()
    {
        var m = new DocSection()
        {
            Title = "Test Model"
        };
        return View(new DocView(), m);
    }
}

The ActionResult/ViewResult classes have a similar interface to the ones in ASP.NET MVC, though they are quite simple so far. The key functionality is in the Execute() method, which actually renders the view. The standard ASP.NET ViewResult writes to the Response, but since this is happening inside a SharePoint page we need to add the content as a control on  the page instead.

public override void Execute()
{
    View.Model = Model;
    View.Execute();
    ParentControl.Controls.Add(new LiteralControl(View.Result));
}

Getting an ActionResult From the subclass and executing it happens in CreateChildControls - I’m not totally sure that is the best place for it, but it seems to be working well so far.

    protected override void CreateChildControls()
    {
        if (!_error)
        {
            try
            {
                base.CreateChildControls();
                var r = Get();
                r.Execute();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
    }

The full code can be found on github.