ASP.NET HTML.BeginForm/Url.Action Url points to it

2019-08-22 23:58发布

I facing an issue with the ASP.NET BeginForm helper.

I try to create a form that should point to /Project/Delete and I tried the following statemant to reach this target:

@using (Html.BeginForm("Delete", "Project"))
{
}

<form action="@Url.Action("Delete", "Project")"></form>

But unfortunately both rendered actions points to /Projects/Delete/LocalSqlServer, which is the url of site called in the browser

<form action="/Project/Delete/LocalSqlServer" method="post"></form>

I really dont know why the rendered action points to itself instead of the given route.I already read all posts (which I found) on google and SO, but found no solution.

This is the only route defined:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

And this are my controller

[HttpGet]
public ActionResult Delete(string id)
{
    return View(new DeleteViewModel { Name = id });
}

[HttpPost]
public ActionResult Delete(DeleteViewModel model)
{
    _configService.DeleteConnectionString(model);
    return null;
}

I am using .NET 4.6.2.

I would really appreciate your help.

Thanks Sandro

1条回答
Ridiculous、
2楼-- · 2019-08-23 00:35

Truth is, it is a bug in asp.net but they refuse to acknowledge it as a bug and just call it a "feature". But, here is how you deal with it...

Here is what my controller looks like:

// gets the form page
[HttpGet, Route("testing/MyForm/{code}")]  
public IActionResult MyForm(string code)
{
    return View();
}

// process the form submit
[HttpPost, Route("testing/MyForm")]
public IActionResult MyForm(FormVM request)
{
    // do stuff
}

So in my case, the code would get appended just like you are getting with the LocalSqlServer.

Here are both versions of how you make a basic asp form:

@using(Html.BeginForm("myform", "testing", new {code = "" }))
{
    <input type="text" value="123" />
}


<form id="theId" asp-controller="testing" asp-action="myform" asp-route-id="" asp-route-code="">
    <input type="text" value="asdf" />

</form>

In the stop where I put asp-route-code, the "code" needs to match the variable in the controller. Same for new {code = "" }.

Hope this helps!

查看更多
登录 后发表回答