asp.net-mvcasp.net-core-mvcasp.net-mvc-controller

ASP.NET MVC Core Tag Helper Issue


I am having an issue using tag helpers in a form element. When I choose the "GET" HTTP method, the parameter for my Edit method in my Item controller won't get filled by the "hello" argument. However, when I choose the "POST" HTTP method, the parameter is filled correctly with "hello". Why is this happening?

<form asp-controller="Item" asp-action="Edit" asp-route-item="hello" method="get">
    <input type="submit" />
</form>

And here is the controller:

    [HttpGet]
    [HttpPost]
    public IActionResult Edit(string item)
    {
        if (Request.Method == "GET")
        {
            ViewData["item"] = item;
            return View();
        }
    }

Solution

  • Nothing to do with the form tag helper. When using HTML form tag, if your are using GET method, the browser will read the form element values and append that to the form action attribute value url following a ?. So i assume your browser is removing your existing query string items for this purpose. So consider moving that to an input element inside the form.

    <form asp-controller="Home" asp-action="Edit" method="get">
        <input type="hidden" name="item" value="second"/>
        <input type="submit"/>
    </form>
    

    Sending the existing querystring values from the action method attribute is not guaranteed to work.. Take look at submitting a GET form with query string params and hidden params disappear