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

眉间皱痕 提交于 2019-12-12 04:59:03

问题


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:


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!



来源:https://stackoverflow.com/questions/45577865/asp-net-html-beginform-url-action-url-points-to-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!