Search code examples
asp.net-mvccontrollerhttp-postaction-filter

Unable to Call a method if i mentioned its attribute as HttpPost


I have a signin page which users can use to signin,i defined its method in controller as HttpPost,when i try to access it from browser,it shows no file found,if i remove the HttpPost attribute it hits the controller and return the view.Eventhough it pass the values in the form to controller if i didnt mentioned its type as HttpPost .Here my code of 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>

And my LoginController Code is here

[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();
    }
}

Solution

  • You need code for both GET and POST.

    You need a GET action to show the form that will be POST'ed

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

    This will show the SignIn view.

    Then you need a POST action to take the values from the form and send them to the controller.

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