回发后模型中的值在控制器中丢失

时间:2015-03-13 06:16:20

标签: c# asp.net-mvc-4 model-view-controller

从视图中选择并执行回发后,我无法获取所选下拉框中的值。我的代码如下

模型中的代码

public class SeleniumModel
    {
        public SeleniumModel()
        {
            BrowserList = new List<SelectListItem>();
            EnviormentList = new List<SelectListItem>();
        }


        public List<SelectListItem> BrowserList
        {
            get;
            set;
        }

        public List<SelectListItem> EnviormentList
        {
            get;
            set;
        }
  }

控制器中的COde

public ActionResult Index()
        {
            SeleniumModel model = new SeleniumModel();
            model.BrowserList.Add(new SelectListItem { Text = "Internet Explorer", Value = "ie" });
            model.BrowserList.Add(new SelectListItem { Text = "FireFox", Value = "firefox" });
            model.BrowserList.Add(new SelectListItem { Text = "Chrome", Value = "chrome" });

            model.EnviormentList.Add(new SelectListItem { Text = "Local", Value = "ie" });
            model.EnviormentList.Add(new SelectListItem { Text = "Dev", Value = "dev" });
            model.EnviormentList.Add(new SelectListItem { Text = "Uat", Value = "uat" });


            return View("Index", model);
        }

视图中的代码

<div class="fields">
                <div>
                    @Html.LabelFor(model => model.Browser)
                    @Html.DropDownListFor(model =>  model.BrowserList,Model.BrowserList)
                </div>
            </div>

                <div class="fields">
                <div>
                    @Html.LabelFor(model => model.Enviornment)
                    @Html.DropDownListFor(model =>  model.EnviormentList,Model.EnviormentList)
                </div>

1 个答案:

答案 0 :(得分:0)

您可能需要修改SeleniumModel以适应您需要的所选浏览器

        public SeleniumModel()
        {
            SelectedBrowser = "";
            BrowserList = new List<SelectListItem>();
            EnviormentList = new List<SelectListItem>();
        }

        public String SelectedBrowser
        {
            get;
            set;
        }

        public List<SelectListItem> BrowserList
        {
            get;
            set;
        }

        public List<SelectListItem> EnviormentList
        {
            get;
            set;
        }

在您的视图中,尝试类似这样的内容

@Html.DropDownListFor(model => model.SelectedBrowser, Model.BrowserList)

当Controller从视图中接受模型时,您将能够使用模型的SelectedBrowser属性获取所选的浏览器。