Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

maintaning drop down selected state after post back in MVC razor?

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).

like image 882
Toubi Avatar asked Nov 25 '13 00:11

Toubi


People also ask

How to keep selected value in dropdown after Submit in asp net?

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.

What is ViewData in razor?

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. {

What is Razor syntax in MVC?

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.


1 Answers

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"}))
like image 116
mnsr Avatar answered Oct 28 '22 04:10

mnsr