Pergunta

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.

Foi útil?

Solução

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>

Outras dicas

You could use POST instead of GET. So you could replace the link with a form containing hidden fields for the parameters that you don't want to appear in the query string:

@using (Html.BeginForm("EventOverview", "BaseEvent", new { id = eventInfo.Key.OID, type = eventInfo.Key.XPObjectType.TypeName.GetShortTypeName() }, FormMethod.Post, null))
{
    @Html.Hidden("activeTab", "#scheduleLink")
    @Html.Hidden("session", eventInfo.Key.EventSchedules[0].SessionId)
    @Html.Hidden("hall", eventInfo.Key.EventSchedules[0].HallId)
    @Html.Hidden("client", eventInfo.Key.EventSchedules[0].BasePlace.PremieraClientId)
    <button type="submit">Make</button>
}

from Darin Dimitrov answer in :

hide parameters passing to controller in address bar (URL rewrite or something else)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top