2011-08-08 113 views

回答

0

假設選定的項目是帖子的一部分,控制器現在知道它是什麼。在ViewData字典中只需輸入一個條目,指示應該選擇哪個項目(獲取時爲null或者如果沒有選擇任何項目)。在視圖中,檢查該值,如果它不爲空,請選擇適當的選項。

1

MVC不使用ViewState,這意味着您將需要自己管理值持久性。通常這是通過你的模型完成的。所以,因爲你有一個視圖模型,如:

public class MyViewModel { } 

而且你的控制器:

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

現在,當你通過模型回的數據視圖(可能不正確 - 驗證失敗) ,當您使用DropDownListFor方法,只是通過在值:

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

...等

MVC的模型綁定將負責將數據讀入模型中,您只需確保將其傳遞迴視圖以再次顯示相同的值。

2

做這樣的事情:

[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(); 
    } 

並在視圖:

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

更容易,您可以在您的ActionResult輸入參數的下拉菜單的姓名(或名稱)。您的下拉列表應該位於表單標籤中。當ActionResult發佈時,ASP.Net將遍歷querystrings,表單值和cookie。只要您包含您的下拉列表名稱,選定的值將被保留。

在這裏我有一個3下拉表單發佈到ActionResult的形式。下拉列表名稱(不區分大小寫):ReportName,Year和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"); 
    } 
0

使用HttpRequestBase對象。 在視圖中,這應該工作:

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

如果你正在建設中的下拉控制器的操作方法列表數據源,你可以選擇的值發送給它

控制器:

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(); 
      } 

查看:

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