0

I have a dropdown menu in a GET form. When the user hits submit, they are directed to the same page and shown the form again. I would like to have the dropdown option the user displayed in the last page already selected. So for example:

 @Html.DropDownList("Type", null, "Type", new { @class = "sbox-input" } )

website.com/Search?Type="Beef"

<select name="Type">
   <option value="Fish" >Fish</option>
   <option value="Chicken" >Chicken</option>
   <option value="Beef" selected="selected">Beef</option>
</select>

A jQuery solution would work just as well.

1 Answer 1

1

I don't think you need javascript to do this as long as you have type parameter in you Action. I assume that you have something like this:

public ActionResult Search(string type, [other parameters])
{
    ....
    ViewBag.SearchType = type; // put the selected type to the ViewBag
}

SelectList takes selectedValue as fourth parameter to it's constructor, so you can easy create DropDownList in the View with the selected value:

@Html.DropDownList("Type", new SelectList(new Dictionary<string, string> { { "Fish", "Fish" }, { "Chicken", "Chicken" }, { "Beef", "Beef" } }, "Key", "Value", ViewBag.SearchType))

Of course you can create the SelectList in the Action and pass it to the View:

public ActionResult Search(string type, [other parameters])
{
    ....
    ViewBag.SearchTypeList = new SelectList(new Dictionary<string, string> { { "Fish", "Fish" }, { "Chicken", "Chicken" }, { "Beef", "Beef" } }, "Key", "Value", type); // you can assign this to the property of your ViewModel if you have one
}

and then in the View

@Html.DropDownList("Type", ViewBag.SearchTypeList)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.