Show only not empty parameters in query string when sumbitting form

Viewed 672

First of all I already saw this: Don't include empty parameters when submitting form

But in form you can have not only input but also select for example and what if someone have Javascript disabled? Isn't there a better way to hide empty parameters?

Let's say I have a form like this:

<form asp-controller="Vehicles" asp-action="Index" method="get" >
<p>
    <select asp-for="Length" asp-items="Model.Lengths">
        <option value="">All</option>
    </select>

    Brand: <input type="text" asp-for="Search">
    <input type="submit" value="Filter" />
</p>
</form>

Now if I picked length from select box and clicked filter, I have this url in the browser window:

https://localhost:44358/Vehicles?Length=15&Search=

but I want this:

https://localhost:44358/Vehicles?Length=15

or if I only searched brand without picking length I want to have this:

https://localhost:44358/Vehicles?Search=Mercedes

Is there some helper tag like adding to form hide-empty="true" or something like that? Any ready to use element or just simple solution for this simple problem?

1 Answers

If you insisit on achieving this requirement, you could try to disable the input which is empty. For disabled field, it will not generate the query string.

Try something like :

<form asp-controller="Vehicles" asp-action="Index" method="get">
    <p>
        Brand: <input type="text" id="Search" name="Search">
        <input type="submit" value="Filter" onclick="return DisableNullFields();"/>
    </p>
</form>

@section Scripts{
    <script type="text/javascript">
        function DisableNullFields() {
        $('input').each(function(i) {
            var $input = $(this);
            if ($input.val() == '')
            $input.attr('disabled', 'disabled');
        });
    }
    </script>
}
Related