简体   繁体   English

使用POST方法的MVC 4发布不起作用(使用GET方法-有效)

[英]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. 当我将表单上的方法从“ GET”更改为“ POST”时,绑定不起作用。 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: 请注意, ActionResult Login不是您的控制者……这是您的操作,请将其添加到操作的标题中:

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

and your form: 和您的表格:

method="POST"

UPDATE* UPDATE *

See that you can explicitly set the name of the view in the return clause. 看到您可以在return子句中显式设置视图的名称。 And if your POST is calling your Login Action it is because you put it explicitly in the action attribute inside your form definition. 而且,如果POST正在调用登录操作,那是因为您将其明确地放在表单定义内的action属性中。

<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. 如果要对GET和POST都执行“操作”,则必须编写两种格式来匹配此定义。

You should probably use: 您可能应该使用:

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

And, as Max said, use return View(); 而且,正如Max所说,请使用return View(); in your Action. 在您的行动中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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