asp.net MVC 4 multiple post via different forms

In an MVC view, you can have as many forms with as many fields as you need. To keep it simple, use a single view model with all the properties you need on the page for every form. Keep in mind that you will only have access to the form field data from the form that you submit. So, if you have a login form and registration form on the same page you would do it like this:

LoginRegisterViewModel.cs

public class LoginRegisterViewModel {
    public string LoginUsername { get; set; }
    public string LoginPassword { get; set; }

    public string RegisterUsername { get; set; }
    public string RegisterPassword { get; set; }
    public string RegisterFirstName { get; set; }
    public string RegisterLastName { get; set; }
}

YourViewName.cshtml

@model LoginRegisterViewModel

@using (Html.BeginForm("Login", "Member", FormMethod.Post, new {})) {

    @Html.LabelFor(m => m.LoginUsername)
    @Html.TextBoxFor(m => m.LoginUsername)

    @Html.LabelFor(m => m.LoginPassword)
    @Html.TextBoxFor(m => m.LoginPassword)

    <input type="Submit" value="Login" />

}

@using (Html.BeginForm("Register", "Member", FormMethod.Post, new {})) {

    @Html.LabelFor(m => m.RegisterFirstName)
    @Html.TextBoxFor(m => m.RegisterFirstName)

    @Html.LabelFor(m => m.RegisterLastName)
    @Html.TextBoxFor(m => m.RegisterLastName)

    @Html.LabelFor(m => m.RegisterUsername)
    @Html.TextBoxFor(m => m.RegisterUsername)

    @Html.LabelFor(m => m.RegisterPassword)
    @Html.TextBoxFor(m => m.RegisterPassword)

    <input type="Submit" value="Register" />

}

MemberController.cs

[HttpGet]
public ActionResult LoginRegister() {
     LoginRegisterViewModel model = new LoginRegisterViewModel();
     return view("LoginRegister", model);
}

[HttpPost]
public ActionResult Login(LoginRegisterViewModel model) {
 //do your login code here
}

[HttpPost]
public ActionResult Register(LoginRegisterViewModel model) {
 //do your registration code here
}

Do not forget, when calling BeginForm, you pass the Controller name without “Controller” attached:

@using (Html.BeginForm("Login", "Member", FormMethod.Post, new {}))

instead of:

@using (Html.BeginForm("Login", "MemberController", FormMethod.Post, new {}))

Leave a Comment