Search code examples
c#asp.netasp.net-mvcactionresult

Cannot apply indexing with [] to an expression of type HttpRequest


I am quite new to programming and I'm trying to learn asp.net web development. I am trying to create a form to take in a username and password which it should then send to the accompanying post action method however when I try to request the data from the action method it comes up with an error saying, 'Cannot apply indexing with [] to an expression of type HttpRequest'. I really don't know what im doing and would appreciate it if someone can tell me what im doing wrong. Thanks!

This is the HTML

@{
    ViewData["Title"] = "Login";
}

<div class="text-center">
    <form method="post" action="Index">
        <label for="username">Username: </label>
        <input type="text"id="username" />

        <label for=" password">Password: </label>
        <input type ="text"id="password" />

        <input type="submit" value="Submit"/>
    </form>
</div>

This is the action method

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ActionName("Index")]
        public IActionResult IndexPost()
        {
            string username = Request["username"];  #This is where the error is happening
            string password = Request["password"];  #Red line under both requests

            -stuff to do-

            return Content("");
        }

Solution

  • ASP.Net has model binding that can be used to automagically bind Action parameters to values POSTed so you should be able to do this

    [HttpPost]
    [ActionName("Index")]
    public IActionResult IndexPost(string username, string password)
    {
        -stuff to do-
    
        return Content("");
    }
    

    The reason for the error is that Request is not indexable like a Dictionary.