maintaning drop down selected state after post bac

2019-04-28 06:38发布

问题:

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

回答1:

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


回答2:

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

Get Action

[HttpGet]
    public ActionResult YourAction()
    {

        ViewBag.SelectedItem = "";
         ///
        return View(new yourViewModel);
    }

Post Action

[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"}))


回答3:

You can use the ? operator which works like this and use the Selected property of the 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 the view u simply put this

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

obviously its not recommended to use viewbag but instead use a model with a list property.