MVVM for Web Development

BDW picture BDW · Aug 6, 2010 · Viewed 16.5k times · Source

I've been reading up on MVVM and so far have found it very interesting. Most of the examples I've found, however, are for Windows apps, as opposed to Web apps. I've also seen a lot of mention of MVVM used with Silverlight, and I know Silverlight can be used for either Web or Windows apps.

So my question is - is MVVM a valid pattern for Web-based apps? If it is, does the UI have to be Silverlight? I'm in the process of deciding which technologies to use for a new mid-size website we need to design, and Silverlight may be a hard sell to the powers-that-be, though what we use behind the scenes doesn't matter so much.

Any info anyone can supply on using MVVM in a web environment would be appreciated. Example code would be great as well.

Answer

Tomáš Herceg picture Tomáš Herceg · Oct 11, 2015

DotVVM is an open source ASP.NET-based MVVM framework based on Knockout JS. It's simple to use and you don't have to write tons of Javascript code. For most scenarios, you need just C# and HTML with CSS.

The view looks like this - it is a HTML extended with server controls and data-bindings:

<div class="form-control">
    <dot:TextBox Text="{value: Name}" />
</div>
<div class="form-control">
    <dot:TextBox Text="{value: Email}" />
</div>
<div class="button-bar">
    <dot:Button Text="Submit" Click="{command: Submit()}" />
</div>

The viewmodel is a C# class which looks like this:

public class ContactFormViewModel 
{
    public string Name { get; set; }
    public string Email { get; set; }

    public void Submit() 
    {
        ContactService.Submit(Name, Email);
    }
}

There is also Visual Studio Extension which adds IntelliSense and project templates.

The framework handles validation, localization, SPAs and other frequently used features. It supports both .NET Framework and .NET Core.