引用DropDownList从封闭Form中选择的值

时间:2016-01-07 01:57:44

标签: asp.net-mvc

我刚开始使用MVC5(来自WebForms),而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方法真的很不错,因为这个View只会列出子实体。

您怎么看?

1 个答案:

答案 0 :(得分: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);
}