4

I have a really wierd issue with MVC. My models keeps getting submitted empty. And it's probably really simple, but I just can't find the issue.

My model looks like this:

public class LoginModel
{
   public string Username;
   public string Password;
}

My controller like this:

[HttpGet]
public ActionResult Login()
{
     return View();
}

[HttpPost]
public ActionResult Login(LoginModel loginTest)
{
      if (loginTest.Username != "x" && loginTest.Password != "y")
      {
           ModelState.AddModelError("a", "Login failed.");
           return View(loginTest);
      }
      else
      {
         return RedirectToAction("Home", "Welcome");
       }

}

And the view is also very simple, like this.

@model LoginSolution.Models.LoginModel
@{
   Layout = null;
}
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Login</title>
    </head>
    <body>
        @using (Html.BeginForm("Login", "Home")) 
        { 
        <div> <span>Username : </span>
            @Html.EditorFor(model => model.Username)
        <br />
            <span>Password : </span>
            @Html.EditorFor(model => model.Password)
        <br />
        @Html.ValidationSummary()
        <br />
        <input type="submit" value="Login" name="Login" />
        </div>
        }
    </body>
    </html>

This is not a question about security or best practice. This is just a question regarding why the model keeps returning itself as empty upon submitting.

2
  • First of all using chrome inspect elemnt, capture what forms send using network tab. Commented Aug 19, 2015 at 7:50
  • 1
    I have the same issue. Even after adding getter/setter model is not working. I always get null object in POST. I have authentication mode="Forms" in web.config Commented Apr 24, 2018 at 8:08

1 Answer 1

11

Your model contains fields, not properties (no getter/setter) so the model binder cannot set the values. Change your model to

public class LoginModel
{
   public string Username { get; set; }
   public string Password { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.