提交表单时不要包含空参数 [英] Don't include empty parameters when submitting form
问题描述
控制器上的index方法如下:
The index method on my controller looks like this:
public ActionResult Index(string search, string sort, int? groupId)
对于搜索功能,我具有以下形式:
For the search functionality, I have the following form:
@using (Html.BeginForm())
{
<div>
@Html.Label("search", "Search")
@Html.TextBox("search", ViewBag.Search as string)
@Html.Hidden("sort", ViewBag.Sort as string)
@Html.Hidden("groupId", ViewBag.GroupId as int?)
<input type="submit" value="Search" />
</div>
}
Viewbag.Search
,ViewBag.Sort
和ViewBag.GroupId
包含最后使用的参数.这些可能是null
或""
,当它们是时,这是我使用搜索表单时看到的URL:
Viewbag.Search
, ViewBag.Sort
and ViewBag.GroupId
contain the last used parameters. These could be null
or ""
, and when they are, this is the URL I see when I use the search form:
...?search=foo&sort=&groupId=
如何隐藏URL中的这些空参数,使其看起来像...?search=foo
?
How can I hide these empty parameters from the URL, so it looks like ...?search=foo
?
编辑:正如Jason Nesbitt所说,您可以禁用隐藏字段以将其从表单中排除.但是,我还想隐藏来自hidden
字段之外的其他内容的空参数,例如常规的input
字段以及select
列表.
as Jason Nesbitt said, you can disable hidden field to exclude them from the form. However, I also want to hide empty parameters that come from other things than hidden
fields, such as regular input
fields, and also select
lists.
推荐答案
如果您要坚持使用GET方法,则可以使用以下事实:浏览器不会发送禁用的字段.因此,绑定到onsubmit处理程序并禁用任何空的隐藏字段,如下所示:
And if you want to stick with the GET method, you can use the fact that browsers won't send disabled fields. So tie into the onsubmit handler and disable any empty hidden fields like the following:
@using (Html.BeginForm("Calculate", "Home", FormMethod.Get, new {onsubmit="DisableNullFields();"}))
{
@Html.TextBoxFor(x => x.Test)
<input type="text" name="TestField" />
<input type="hidden" name="hidden" value="" />
<input type="submit" value="Push"/>
}
<script>
function DisableNullFields() {
$('input[type=hidden]').each(function(i) {
var $input = $(this);
if ($input.val() == '')
$input.attr('disabled', 'disabled');
});
}
</script>
这篇关于提交表单时不要包含空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!