0

I have created a DropDownList which is initialized from code behind like that :

Code Behind :

List<SelectListItem> ddlIsActivated = new List<SelectListItem>
{
    new SelectListItem
    {
        Text = "Activated",
        Value = "0"
    },
    new SelectListItem
    {
        Text = "Not activated",
        Value = "1"
    }
};

ViewBag.ddlIsActivated = ddlIsActivated;

View :

<div class="row">
    <div class="form-group col-xs-3">
        @Html.DropDownList("IsActivated", ViewBag.ddlIsActivated as List<SelectListItem>, "Default")
    </div>
</div>

When I click directly on the search button after the load, the DropDownList has "Default" as the first item and my URL looks like that :

http://localhost:51817/Log?SearchString=&IsActivated=

Is it possible to specify that all parameters with an empty value might not be passed on the URL ? In case of the DropDownList, is it possible to avoid the param "IsActivated" when the "Default" is Selected ?

wytes
  • 421
  • 7
  • 24

2 Answers2

0

Sure one way is when the submit button is clicked or activated, you set the fields that are the default value to disabled. then they don't go in the post.

Example of using jQuery onsubmit:

How to use jQuery to onsubmit and check if the value is 2 - 5 characters?

Community
  • 1
  • 1
Maslow
  • 18,464
  • 20
  • 106
  • 193
  • there is no Attribute or something else than JQuery to manage the empty values for each parameter ? – wytes May 09 '14 at 14:43
  • no this would be something clientside to help the browser decide not to post values that are not changed by the client. – Maslow May 09 '14 at 14:59
0

You can try having a separate viewmodel, with properties for the list of options and the selected option. In the GET request action method, you can populate this list and render the view, and in the POST action method, you can exclude this property during model binding, so that only the selected item property will get bound. Thus, you don't need ViewBag or routeValues or querystring parameters, and your URL will always look clean.

EDIT:

This is how you might do it.

public class ViewModel
{
    public int SelectedId { get; set; }
    public Dictionary<int,string> OptionList { get; set; }
}

And then in your view,

@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.OptionList, "Key", "Value"), null, null)

In your GET action method,

Dictionary<int,string> OptionList = GetOptionList(); // Populate from DB
return View(new ViewModel { OptionList = OptionList });

Also, remember to [Bind(Exclude="OptionList")] in your POST action method.

Bhushan Shah
  • 1,028
  • 8
  • 20
  • I don't really understand your example. Do you have any code example or online documentation to clearly understand this and how to implement it ? I initially not used the ViewBag but someone suggest me the ViewBag in this post http://stackoverflow.com/questions/23563138/creating-a-dropdownlist/23563292?noredirect=1#23563292 – wytes May 09 '14 at 14:42