user584018
user584018

Reputation: 11304

ViewData with DropDown

I'm using MVC3/Razor and want to bind a DropDownList with some data like below,

 @Html.DropDownList("SearchBy", new[] {     new SelectListItem { Text = "Order ID", Value = "OrdId" }, 
                                            new SelectListItem { Text = "Mobile Number", Value = "MobileNum" }, 
                                            new SelectListItem { Text = "Clerk Name", Value = "ClerkName" },
                                            new SelectListItem { Text = "Pin Number", Value = "PinNum" },
                                            new SelectListItem { Text = "RTS PayGo Ref ID", Value = "RefId" } })

The above code bind the DropDownList with respected data. Currently "Order ID" is default selected.

If user do a post action, I'm able to send the selected value to my controller.

How can we set that value to ViewData/ViewBag, so that selection of DropDownList will persist after postback?

Upvotes: 1

Views: 668

Answers (1)

Brian Mains
Brian Mains

Reputation: 50728

On every action post, you'd have to continually add the item to the ViewBag or ViewData and manually keep updating it, or store it in session. Everytime you reload the view, you have to set the selected value to match.

HTH.

Upvotes: 1

Related Questions