如何使用属性路由定义Html.BeginForm以进行操作? [英] How to define Html.BeginForm for action with attribute routing?

查看:142
本文介绍了如何使用属性路由定义Html.BeginForm以进行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

查看

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

渲染的HTML

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

我之所以使用[HttpGet],部分原因是我希望通过http://myapp.com/search/<search values>

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

当我导航到http://myapp.com/search/test时,一切似乎都很好,但是当我尝试在文本框中输入新的搜索字词并按Enter或Submit时,它导航到http://myapp.com/search?clause=newsearch

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

我应该怎么做才能使我的文本框导航到http://myapp.com/search/newsearch?

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

推荐答案

您的表单会生成http://myapp.com/search?clause=newsearch,因为浏览器不知道您的路由(服务器上运行的c#代码).

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

为了生成首选的URL(http://myapp.com/search/newsearch),您需要使用JavaScript来拦截和取消默认的提交,并构建一个URL进行导航.使用jQuery:

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
});

这篇关于如何使用属性路由定义Html.BeginForm以进行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆