开发者

How to keep dropdownlist selected value after postback

开发者 https://www.devze.com 2023-03-26 10:01 出处:网络
In asp.net mvc3 how to keep dropdown list开发者_开发百科 selected item after postback.Do something Like this :

In asp.net mvc3 how to keep dropdown list开发者_开发百科 selected item after postback.


Do something Like this :

[HttpPost]
    public ActionResult Create(FormCollection collection)
    {  if (TryUpdateModel(yourmodel))
            { //your logic 
              return RedirectToAction("Index");
            }
          int selectedvalue = Convert.ToInt32(collection["selectedValue"]);
           ViewData["dropdownlist"] = new SelectList(getAllEvents.ToList(), "EventID", "Name", selectedvalue);// your dropdownlist
            return View();
     }

And in the View:

 <%: Html.DropDownListFor(model => model.ProductID, (SelectList)ViewData["dropdownlist"])%>


Even easier, you can include the name(s) of your dropdowns in your ActionResult input parameters. Your dropdowns should be in form tags. When the ActionResult is posted to, ASP.Net will iterate through querystrings, form values and cookies. As long as you include your dropdown names, the selected values will be preserved.

Here I have a form with 3 dropdowns that posts to an ActionResult. The dropdown names are (non-case sensitive): ReportName, Year, and Month.

    //MAKE SURE TO ACCEPT THE VALUES FOR REPORTNAME, YEAR, AND MONTH SO THAT THEY PERSIST IN THE DROPDOWNS EVEN AFTER POST!!!!
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ReportSelection(string reportName, string year, string month)
    {
        PopulateFilterDrowdowns();
        return View("NameOfMyView");
    }


MVC does not use ViewState, which means you will need to manage the value persistence yourself. Typically this is done through your model. So, given that you have a view model, e.g.:

public class MyViewModel { }

And your controller:

public class MyController : Controller 
{
    public ActionResult Something()
    {
        return View(new MyViewModel());
    }

    public ActionResult Something(MyViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        return RedirectToAction("Index");
    }
}

Now, when you pass the model back to the view with data (probably incorrect - failed validation), when you use your DropDownListFor method, just pass in the value:

@Model.DropDownListFor(m => m.Whatever, new SelectList(...))

... etc.

MVC's model binding will take care of the reading of the data into your model, you just need to ensure you pass that back to the view to show the same value again.


Assuming the selected item is part of the post, the controller now knows what it is. Simply have an entry in the ViewData dictionary indicating which item should be selected (null on get or if nothing was selected). In the view, check the value and if it's not null, select the appropriate option.


Use HttpRequestBase object. In the view, this should work:

 @Html.DropDownList("mydropdown", ViewBag.Itens as IEnumerable<SelectListItem>, new { value = Request["mydropdown"] })


If you are building the drop down list data source in the controller Action Method you can send the selected value to it

Controller:

 public ActionResult Index( int serviceid=0)
            {


             // build the drop down list data source
                List<Service> services = db.Service.ToList();
                services.Insert(0, new Service() { ServiceID = 0, ServiceName = "All" });
               // serviceid is the selected value you want to maintain
                ViewBag.ServicesList = new SelectList(services, "ServiceID", "ServiceName",serviceid);

               if (serviceid == 0)
                {
                    //do something
                }
                else
                {
                     // do another thing

                }
                return View();
           }

View:

 //ServiceList is coming from ViewBag
@Html.DropDownList("ServicesList", null, htmlAttributes: new { @class = "form-control" })
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号