Form for a different model than the view page in ASP.NET MVC 3

I have find out 2 more ways

  1. Override the Name attribute for TextBoxFor and set it as the property name.
    var formModel = new ForgotPasswordFormModel();
    @Html.TextBoxFor(m => formModel.UsernameOrEmail, new { Name = "UsernameOrEmail" })
  1. Specify the same exact model name as the post method parameter.
    var formModel = new ForgotPasswordFormModel();
    @using (Html.BeginForm("ChangePassword", "LoginSurface")
    {
       @Html.TextBoxFor(m => formModel.UsernameOrEmail)
    }
    ...
    public virtual ActionResult ChangePassword(ForgotPasswordFormModel formModel)

You could create another HtmlHelper like this

var emailSignupHtml = new HtmlHelper<EmailSignup>(Html.ViewContext, new ViewDataContainer<EmailSignup>(new EmailSignup()));

and use it like this

@emailSignupHtml.TextBoxFor(m => m.Email)

For the ViewDataContainer I use following helper class

public class ViewDataContainer<TModel> : ViewDataDictionary<TModel>, IViewDataContainer
{
   public ViewDataContainer(TModel model) : base (model)
   {
      ViewData = new ViewDataDictionary(model);
   }

   public ViewDataDictionary ViewData { get; set; }
}

This can be done quite easily. You just have to do it like this:

var contactModel = new ContactModel();
@Html.TextBoxFor(m => contactModel.Title)
@Html.ValidationMessageFor(m => contactModel.Title)

The validation works like a charm.


Move the form to a partial view that takes an EmailSignup model.