asp.net MVC 4 multiple post via different forms

Davidred15 picture Davidred15 · Apr 3, 2013 · Viewed 93.5k times · Source

Right now I understand

if (IsPost){   //do stuff }

checks all post methods on that page. However, I have 2 different forms posting 2 different information. These are a login form and a register form.

Is there a way I can check IsPost based on which form? For example,

if(Login.IsPost){ //do stuff }

but how would I define the Login variable? My form looks like:

<form id="Login" method = "POST">

I have tried:

var Login = Form.["Login"]

it did not work.

I will appreciate any help.

Thanks.

Answer

jpshook picture jpshook · Apr 4, 2013

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 {}))