Search code examples
c#asp.net-coreasp.net-core-mvc

asp-action inside form doesn't go to controller


I have a form :

@model TodoItem
<form asp-action="/Todo/AddItem" method="POST">
    <label asp-for="Title">Add a new item:</label>
    <input asp-for="Title">
    <button type="submit">Add</button>
</form>

I call it in the Index.html

@await Html.PartialAsync("AddItemPartial", new TodoItem())

that calls the controller on button click :

public async Task<IActionResult> AddItem(TodoItem newItem)
{ 
  //code that calls service...
}

I never hit a breakpoint on AddItem, I read that it might be from the asp-action not firing due to _ViewImports.cshtml not being in the same folder or that it didn't cointain @addTagHelper. Tried those solutions, but didn't work.

Any help would be appreciated.


Solution

  • I think when you use asp-action, you should only specify action name and not the complete path.

    For ex. If below is the code in your page:

    <form asp-controller="Demo" asp-action="Register" method="post">
        <!-- Input and Submit elements -->
    </form>
    

    This code is converted to below code:

    <form method="post" action="/Demo/Register">
        <!-- Input and Submit elements -->
        <input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
    </form>
    

    Please check that after the server side code converted to HTML, there is no asp-action, there is only action attribute understood by HTML form.

    For you, you will have to change code to :

    @model TodoItem
    <form asp-controller="Todo" asp-action="AddItem" method="POST">
        <label asp-for="Title">Add a new item:</label>
        <input asp-for="Title">
        <button type="submit">Add</button>
    </form>
    

    Hope this helps.