Riley Varga
Riley Varga

Reputation: 720

Why are my model properties null when trying to POST?

So I'm trying to create a login page and I've created a form that posts to a action inside the controller.

This is what the controller looks like, very simple, just for testing purposes.

public ActionResult Verify(User account)
{
    var s = account;
    if (db.Users.Any(o => o.Username == ""))
    {
        // Match!
    }
    return Redirect("https://google.se");
}

And here is the HTML

<form id="form1" method="post" action="Verify">
    <!-- Input and Submit elements -->
    <div class="form-group">
        <input type="email" class="form-control form-control-user" id="Username" name="Username" aria-describedby="emailHelp" placeholder="Enter Email Address...">
    </div>
    <div class="form-group">
        <input type="password" class="form-control form-control-user" name="PasswordHash" placeholder="Password">
    </div>
    <a href="Verify" type="submit" class="btn btn-primary btn-user btn-block" >
        Login
    </a>
    <hr>
</form>

When I click Login it does invoke the Verify action, however the parameter I'm passing in account all the properties are null and I'm not sure why.

Upvotes: 2

Views: 172

Answers (1)

MikNiller
MikNiller

Reputation: 1280

You are not really submitting the form, unless some javascript event does that for you.

Try changing

<a href="Verify" type="submit" class="btn btn-primary btn-user btn-block" >
    Login
</a>

to a submit button instead

<button type="submit" class="btn btn-primary btn-user btn-block" >
     Login
</button>

When you use a link then you are making a GET request which wont post your form data to the controller, in chrome you can see that for yourself in developer tools/network, open that and then click Login, this should result in the Verify request showing up in the list of requests.

If you really want to use a link and not a submit button, then you can add a bit of javascript to submit your form, either by adding a event handler or submitting the form directly from the link's onClick method.

<a href="Verify" onclick="document.getElementById('form1').submit();" class="btn btn-primary btn-user btn-block" >
    Login
</a>

Upvotes: 4

Related Questions