我的控制器上的索引方法如下所示:
public ActionResult Index(string search, string sort, int? groupId)
对于搜索功能,我有以下形式:
@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
and ViewBag.GroupId
包含最后使用的参数。这些可能是null
or ""
,当它们出现时,这是我使用搜索表单时看到的 URL:
...?search=foo&sort=&groupId=
我怎样才能从URL中隐藏这些空参数,所以它看起来像...?search=foo
?
EDIT:正如 Jason Nesbitt 所说,您可以禁用隐藏字段以将它们从表单中排除。但是,我也想隐藏来自其他事物的空参数hidden
字段,例如常规字段input
领域,还有select
lists.
如果您想坚持使用 GET 方法,您可以利用浏览器不会发送禁用字段的事实。因此,绑定到 onsubmit 处理程序并禁用任何空的隐藏字段,如下所示:
@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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)