Rob
Rob

Reputation: 1579

Using ViewModels in ASP.NET MVC 2 - multiple forms

I couldn't find any documentation around using multiple forms in an ASP.NET MVC 2 ViewModel approach.

i.e. In the built in application when you select New MVC2 web app, the register page uses a ViewPage which inherits like this:

Inherits="System.Web.Mvc.ViewPage<rs30UserWeb.Models.RegisterModel>"

I wanted to use that approach on a page with multiple forms, but that RegisterModel only supported one form.

Upvotes: 2

Views: 1532

Answers (1)

Rob
Rob

Reputation: 1579

The approach is to use a composite viewmodel:

namespace MyApp.Models
{
    public class MyCompositePageModel
    {
        public RegisterModel registerModel;
        public LoginModel loginModel;
    }
}

When you do that, inherit the View from it:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<rs30UserWeb.Models.RegisterModel>" %>

Then reference the individual models in the page:

<%= Html.TextBoxFor(m => m.loginModel.Email) %>
<%= Html.ValidationMessageFor(m => m.loginModel.Email) %>

Hope someone else finds this useful.

Upvotes: 5

Related Questions