In a MVC 4 Web I have drop-down lists with the below sample code:
@(Html.DropDownList("Condition2", new SelectList(Model.Makes, "CCultureId", "CTitle"), "All",new {@class="span3"}))
I have All as a first option in select and on button press, page shows data in it. After post back, drop downs got reset on button press, can you please guide me how to make drop down keeping its state even after page post backs (I understand in MVC4 there are no postback, I m reffering it as a round trip to server).
You have (minimum) 2 options: 1) If you do not need any server side processing after clicking 'Cancel Button', you can use JavaScript and write history.go(-1) onclick of the button. That will take you to the previous page and drop-down-list will show the last selected value.
ViewData is a container for data to be passed from the PageModel to the content page. ViewData is a dictionary of objects with a string-based key. You add items to ViewData as follows: public class IndexModel : PageModel. {
Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.
One way to do it is, in your controller, return the submitted value in the model. This means your dropdownlist should be hooked up to your viewmodel.
ViewModel:
public class MyViewModel
{
// more properties...
public string Make {get;set;}
// more properties
}
Controller:
[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
// do postback stuff
return View(model); // model.Make is set to whatever was submitted and will be returned
}
Html:
@model Models.MyViewModel
@(Html.DropDownListFor(m => m.Make,
new SelectList(Model.Makes, "CCultureId", "CTitle", Model.Make),
"All", new {@class="span3"}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With