Search code examples
c#asp.netasp.net-corebuttonasp.net-core-tag-helpers

Passing parameter to Controller from view with tag helpers not working on a submit


I'm using ASP.NET Core 2.2.

I'm trying to pass an ID (Guid) from my view to my controller Index using a submit button decorated with asp tag helpers like below:

<input type="submit" value="Go" asp-controller="MyController" asp-action="Index" asp-route-id="@Model.Id" />

My controller action method looks like this:

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

The id is always coming through as Guid.Empty when the submit button is clicked.

I've switched over to using an anchor tag with the same tag helper values and the id comes through populated correctly:

<a asp-controller="MyController" asp-action="Index" asp-route-id="@Model.Id">Go</a>

I can get around this by styling an anchor to look like a button, but for the sake of understanding, can someone explain why an anchor would work in this situation but a submit button will not?

UPDATED (with generated HTML)

HTML with submit

<form>
    <div class="d-flex">
        <input type="submit" value="Go" formaction="" />
    </div>
</form>

HTML with anchor

<form>
    <div class="d-flex">
        <a href="/MyController?Id=2590bc68-6784-4174-90f5-e7ceb1b4d0e9">Go</a>
    </div>
</form>

Solution

  • put the asp-route-id="..." in the form tag, not in the button.