Yousuf
Yousuf

Reputation: 3275

asp.net core mvc application form post with query string parameters

I am building a login form in .net core mvc. Below is my login form

<form class="c-form" asp-controller="Account"
  asp-action="Login">
<div class="form-group">
    @Html.TextBoxFor(m => m.Username, new { @class = "form-control c-input", placeholder = "Username" })
</div>

<div class="form-group">
    @Html.PasswordFor(m => m.Password, new { @class = "form-control c-input", placeholder = "Password" })
</div>
<div class="help-text help-text-error">
    @Html.ValidationMessage("UserNamePasswordInvalid")
</div>
<div class="">
    <button type="submit" class="btn-c btn-teal login-btn width100">Login</button>
</div>

If a form is posted with incorrect credentials user stays on the page with validation failure messages.

Login page also has return url in query string, when the form is posted query string parameters are lost. What is the correct way of doing form post in .net core.

Upvotes: 6

Views: 11660

Answers (4)

Ali
Ali

Reputation: 2150

If the controller and action pair for getting and posting the form is the same, than it is simpler to just delete asp-controller and asp-action attributes from the form opening tag, leaving your like this:

<form class="c-form" method="post">

Upvotes: 0

Doug Dekker
Doug Dekker

Reputation: 353

Your controller/PageModel method must contain all parameters that you need to persist. Something like this:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)

Upvotes: 0

mirko federico
mirko federico

Reputation: 19

I know that it's passed a lot of time, but I found a better solution for this problem.

I added a parameter called QueryString in Model as Dictionary string

in view, in tag form, add

So at this time, the post have the parameters in query string<form asp-all-route-data="@Model.QueryString"

Upvotes: 1

connectedsoftware
connectedsoftware

Reputation: 7087

To keep the query string when the form is submitted write a hidden field in the form containing the query string contents:

@Html.Hidden("returnUrl",@Request.QueryString)

Make sure your controller action that handles the post request has a parameter called returnUrl (or the model that is passed as a parameter has that property) and the model binding will take care of passing it through to the controller. Then in the controller action if the login is successful use that data to redirect accordingly.

Upvotes: 10

Related Questions