2017-08-08 188 views
0

我遇到ASP.NET BeginForm幫助程序的問題。ASP.NET HTML.BeginForm/Url.Action Url指向自己

我試圖創建應指向/Project/Delete一種形式,我嘗試了以下衆所周知聲明來實現這一目標:

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

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

但不幸的是渲染操作點既/Projects/Delete/LocalSqlServer,這是網站的所謂的網址瀏覽器

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

我真的不知道爲什麼渲染的動作指向自身,而不是給出route.I已經閱讀谷歌的所有帖子(我發現)和SO,但沒有發現任何解決方案。

這是定義的唯一途徑:

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

這是我的控制器

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

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

我使用.NET 4.6.2。

我真的很感謝你的幫助。

感謝 桑德羅

+0

我碰到類似的東西,會看看我是否能找到你的github問題。 – nurdyguy

+0

你能告訴我們刪除操作方法嗎? – Win

+0

您需要顯示您的路由定義以及'[HttGet]'和'[httpPost]'方法 –

回答

1

事實是,它是在asp.net一個錯誤,但他們拒絕承認它作爲一個bug,只是稱其爲「功能」。但是,這裏是你如何對待它...

這裏是我的控制器是什麼樣子:

// 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 
} 

所以在我的情況下,code會得到追加就像你與LocalSqlServer獲得。

下面是你如何做一個基本的ASP形式的兩個版本:

@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> 

在這裏我把asp-route-code停止,「代碼」需要的變量在控制器相匹配。相同的new {code = "" }

希望這會有所幫助!

+0

此解決方案適用於我,謝謝@nurdyguy。 –