why does razor make form with empty action?

发布时间 2023-07-26 15:28:42作者: ChuckLu

why does razor make form with empty action?

I create a form with razor to have specific controller and action with asp-controller and asp-action but after razor render the page, I get form with empty action. I do not know why

<form asp-controller="PanelController" asp-action="AddCatAndSubAndBrand" method="post">

but result in html is

<form method="post" action="">

I put @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers in _viewImports

 

回答

You need to drop the word Controller, if your controller class name is PanelController you just use "Panel". Its a convention. Since it doesn't find the controller based on conventions it doesn't render the action.

<form asp-controller="Panel" asp-action="AddCatAndSubAndBrand" method="post">

 

想要正确render form的action attribute,必须确保对应的Controller和Action存在。并且指定asp-controller的时候要省略Controller后缀

 

遇到类似的问题,需要排查cotroller和action是否存在

 

The Route attribute is important for routing in ASP.NET Core, and its absence could lead to unexpected behavior, including empty URLs in your Razor views.

In ASP.NET Core, the Route attribute is used to specify the route template for an action method. Without it, the framework may not be able to resolve the correct URL for the action, especially if there are multiple actions with similar names or the default route template does not match your intended URL structure.

To fix the issue, you should add the Route attribute to your controller or action method, specifying the route template that corresponds to the desired URL path.