Maintaning dropdown selected state after message in MVC razor?

In MVC 4 Web, I have drop-down lists with the following code example:

@(Html.DropDownList("Condition2", new SelectList(Model.Makes, "CCultureId", "CTitle"), "All",new {@class="span3"})) 

I have everything as the first option when I press and press the button, the data is displayed on the page. After you go back, the pop-up buttons got reset when the button was clicked, can you advise me how to make the drop out, keeping my state, even after the page has been reversed (I understand that in MVC4 there is no postback, I repeat this as round-trip to the server).

+6
source share
3 answers

One way to do this is to return the presented value to the model in your controller. This means that your dropdownlist must be connected to your view model.

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"})) 
+7
source

You can use the Viewbag to save the selected item, see blew:

Get action

 [HttpGet] public ActionResult YourAction() { ViewBag.SelectedItem = ""; /// return View(new yourViewModel); } 

Action Message

 [HttpPost] public ActionResult YourAction(FormCollection form,YourViewModel model) { ViewBag.SelectedItem = form["Condition2"]; /// return View(model); } 

View

 @(Html.DropDownList("Condition2", new SelectList(Model.Makes, "CCultureId", "CTitle",ViewBag.SelectedItem), "All",new {@class="span3"})) 
0
source

You can use? statement that works like this and uses the Selected property of selectlistitem

 Console.WriteLine((2 == 2 ? "true" : "false")); 

and then for example

 private Entities en = new Entities(); public ActionResult Index(string selectedvalue) { List<SelectListItem> selectlist = en.tblUser.Select(x => new SelectListItem { Text = x.Name, Value = x.Id, Selected = ( x.Name == selectedvalue ? false : true) }) .ToList(); ViewBag.DropDown = selectlist; return View(); } 

then in u view just put this

 @Html.DropDownList("DropDownName", (List<SelectListItem>)ViewBag.DropDown)) 

Obviously, it is not recommended to use a viewbag, but instead use a model with a list property.

0
source

Source: https://habr.com/ru/post/958748/


All Articles