How to define Html.BeginForm for action with attribute routing?

痴心易碎 提交于 2019-12-12 09:46:41

问题


Controller

[HttpGet]
[Route("~/search/{clause}/{skip?}")]
public async Task<ActionResult> Search(string clause, int skip = 0)
{
   ...
}

View

@using (Html.BeginForm("Index", "search", FormMethod.Get))
{
    @Html.TextBox("clause", null, new { @class = "form-control col-md-4" })
    ...
}

Rendered Html

<form action="/search" method="get">
    <input id="clause" name="clause" type="text" value="test">
</form>

I am using [HttpGet] partly because i want the search to be accessing via http://myapp.com/search/<search values>

When i navigate to http://myapp.com/search/test, everything seems fine, but when i try to enter my new search term in the textbox and hit enter or submit, it navigates to http://myapp.com/search?clause=newsearch

What should I do so that my textbox will navigate to http://myapp.com/search/newsearch instead?


回答1:


Your form generates http://myapp.com/search?clause=newsearch because a browser has no knowledge of your routes (c# code running on your server).

In order to generate your preferred url (http://myapp.com/search/newsearch), you need javascript to intercept and cancel the default submit, and build a url to navigate to. Using jQuery:

$('form').submit(function() {
    var baseUrl = $(this).attr('action'); // or var baseUrl = '@Url.Action("Index", "search")';
    var url = baseUrl + '/' + $('clause').val(); // add value for skip if required
    location.href = url; // redirect
    return false; // cancel the default submit
});


来源:https://stackoverflow.com/questions/25886562/how-to-define-html-beginform-for-action-with-attribute-routing

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