简体   繁体   中英

MVC 4 posting with POST method doesn't work (with GET method - works)

This is my model:

public class LoginModel {
    public string username { get; set; }
    public string password { get; set; }
    public string ReturnUrl { get; set; }
}

This is my controller header:

    [AllowAnonymous]
    public ActionResult Login(
        LoginModel model
    )

This is my view:

 <form action="@Url.Action("Login", "Login")" method="GET">
        @Html.HiddenFor(m=>m.ReturnUrl)
        User name: @Html.TextBoxFor(f=>f.username)
        <br />
        Password: @Html.PasswordFor(f=>f.password)
        <br /><br />
        <button type="submit">Login</button>
    </form>

When I change the method on the form from "GET" to "POST" the binding doesn't work. I tried to add:

[AcceptVerbs("POST", "GET")]

to the controller header, it doesn't help

Be carefull , ActionResult Login is not your controller... it is your Action, add this in the header of your action:

[HttpPost] 
public ActionResult Login(LoginModel model)
{
  // your code
  return View("NameofView"); //**UPDATE
}

and your form:

method="POST"

UPDATE*

See that you can explicitly set the name of the view in the return clause. And if your POST is calling your Login Action it is because you put it explicitly in the action attribute inside your form definition.

<form action="<Here_your_action>" method="POST">

If you want to do both "actions" for GET and POST, you must code two forms to match this definition.

You should probably use:

@using (Html.BeginForm())
{
  @Html.TextBoxForm(model => model.MyField)
}

And, as Max said, use return View(); in your Action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM