2016-01-07 78 views
0

我剛剛開始使用MVC5(來自WebForms),並且dropdownlist綁定給了我一些適合。引用DropDownList從封閉表格中選擇值

我想使用GET請求返回頁面,使用選定的值參數來工作。我希望我可以在表單中指定路由參數,所以我想引用DDL的SelectedValue。

<p> 
    @using (Html.BeginForm("Index", "Profile", FormMethod.Get, new { id = WHATDOIPUTHERE})) { 
     @Html.AntiForgeryToken() 

     @Html.DropDownList("ApplicationID", new SelectList(ViewBag.ApplicationList, "ApplicationID", "ApplicationName", ViewBag.SelectedApplicationId), new {onchange = "this.form.submit();"}) 
    } 
</p> 

我可以把它用POST形式工作,但需要第二個控制器的方法,所以我結束了

public ActionResult Index(long? id) { 
    ConfigManager config = new ConfigManager(); 

    //handle application. default to the first application returned if none is supplied. 
    ViewBag.ApplicationList = config.GetApplications().ToList(); 

    if (id != null) { 
     ViewBag.SelectedApplicationId = (long)id; 
    } 
    else { 
     ViewBag.SelectedApplicationId = ViewBag.ApplicationList[0].ApplicationID; //just a safe default, if no param provided. 
    } 

    //handle profile list. 
    List<ProfileViewModel> ps = new List<ProfileViewModel>(); 
    ps = (from p in config.GetProfilesByApp((long)ViewBag.SelectedApplicationId) select new ProfileViewModel(p)).ToList(); 

    return View(ps); 
} 

//POST: Profile 
//read the form post result, and recall Index, passing in the ID. 
[HttpPost] 
public ActionResult index(FormCollection collection) { 
    return RedirectToAction("Index", "Profile", new {id = collection["ApplicationId"]}); 
} 

這將是非常好的擺脫POST方法,因爲此視圖只會列出子實體。

您認爲如何?

回答

1

您可以將您的GET操作方法參數名稱更新爲與您的下拉名稱相同。

我也做了一些小的修改,以避免可能的空引用異常。

public ActionResult Index(long? ApplicationID) { 

    var config = new ConfigManager(); 

    var applicationList = config.GetApplications().ToList(); 
    ViewBag.ApplicationList = applicationList ; 

    if (ApplicationID!= null) { 
     ViewBag.SelectedApplicationId = ApplicationID.Value; 
    } 
    else 
    { 
     if(applicationList.Any()) 
     { 
     ViewBag.SelectedApplicationId = applicationList[0].ApplicationID; 
     } 
    } 

    var ps = new List<ProfileViewModel>(); 
    ps = (from p in config.GetProfilesByApp((long)ViewBag.SelectedApplicationId) 
               select new ProfileViewModel(p)).ToList(); 

    return View(ps); 
} 
+1

這是一個很好的解決方案。非常感謝你。 –

+0

不客氣!很高興我能幫上忙 :) – Shyju