【问题标题】:Unable to Call a method if i mentioned its attribute as HttpPost如果我将其属性称为 HttpPost,则无法调用方法
【发布时间】:2017-07-24 16:48:50
【问题描述】:

我有一个用户可以用来登录的登录页面,我在控制器中将其方法定义为 HttpPost,当我尝试从浏览器访问它时,它显示未找到文件,如果我删除 HttpPost 属性它会命中控制器并返回视图。即使它将表单中的值传递给控制器​​,如果我没有提到它的类型为 HttpPost 。这是我的 Login/SignIn.cshtml 代码:

@model BOL.Player_Access
@using (Html.BeginForm("SignIn","Login",FormMethod.Post)){
@Html.AntiForgeryToken()
 <div class="form-horizontal">
    <h4>Sign In</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.PlayerEmail, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PlayerEmail, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PlayerEmail, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="SignIn" class="btn btn-default" />
        </div>
    </div>
</div>

我的 LoginController 代码在这里

[AllowAnonymous] //This filter removes authorize filter for this controller alone and allow anonyomous request
public class LoginController : Controller
{
    // GET: Login
    public ActionResult Index()
    {
        return View();
    }

   [HttpPost]
    public ActionResult SignIn(Player_Access plyr_obj)
    {
        return View();
    }
}

【问题讨论】:

  • 发布您的完整代码视图。缺少端花括号。

标签: asp.net-mvc controller http-post action-filter


【解决方案1】:

您需要 GET 和 POST 的代码。

您需要一个 GET 操作来显示将要发布的表单

public ActionResult SignIn()
{
    return View();
}

这将显示登录视图。

然后您需要一个 POST 操作来从表单中获取值并将它们发送到控制器。

[HttpPost]
public ActionResult SignIn(Player_Access plyr_obj)
{
    //do some work to authenticate the user

    return View();
}

【讨论】:

  • ,它有效..谢谢。但是这是完成这个兄弟的正确方法吗,我不能在一个功能中实现它吗?我在视频教程中看到,他们对两者都使用了单一的操作方法发布数据和显示表单都在一个动作中。关于他们如何实现它的任何想法兄弟,MVC 是否在任何旧版本中支持此功能?
  • 我不知道任何“支持”单一显示/发布语义的 MVC 版本。在最琐碎的情况下可能会起作用,但是一旦您开始在页面上显示未回发的属性(例如选择列表),它就会崩溃。
  • 还研究了 PRG 模式。发布后,您应该重定向回 Create Get 或 Index,这样您就不会意外地连续多次发布。这里有一个很好的解释stevefenton.co.uk/2011/04/asp-net-mvc-post-redirect-get-pattern
猜你喜欢
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
相关资源
最近更新 更多