Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't include empty parameters when submitting form

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

How can I hide these empty parameters from the URL, so it looks like ...?search=foo?


EDIT: 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.

like image 848
Rudey Avatar asked Sep 15 '25 14:09

Rudey


1 Answers

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>
like image 132
Jason Nesbitt Avatar answered Sep 18 '25 06:09

Jason Nesbitt