你的位置:首页 > ASP.net教程

[ASP.net教程]MVC dropdownlist使用

View中代码

@{  ViewBag.Title = "dropdownlist";}<h2>dropdownlist</h2>@using (Html.BeginForm()){  <table>    <tr>      <td>test1</td>      <td>        <input type="radio" id="GenderM" name="Sex" value="男" />男        <input type="radio" id="GenderF" name="Sex" value="女" checked />女        <input type="text" id="1" name="1" value="1">      </td>    </tr>    <tr>      <td>test2</td>      <td>        @Html.DropDownList("name", ViewBag.selList1 as IEnumerable<SelectListItem>)      </td>    </tr>  </table>  <input type="submit" value="submit">

Control中代码 

public ActionResult dropdownlist()    {      var q = from p in modeltest.Students select p;      List<student> droptest = q.ToList();      SelectList selList1 = new SelectList(droptest,"id","name");      ViewBag.selList1 = selList1.AsEnumerable(); //选择数据库数据绑定      return View();    }        [HttpPost]    public ActionResult dropdownlist(string test="test")    {      var q = from p in modeltest.Students select p;      List<student> droptest = q.ToList();      ViewData["name"] = new SelectList(droptest,"id","name");   //重构dropdownlist      var name = modeltest.Students.Find(Convert.ToInt32(Request.Form["name"]));      formtest fm = new formtest { id = Convert.ToInt32(Request.Form["1"]), value1 = Request.Form["sex"], value2 = name.name }; //通过view中的数据给model对象赋值      modeltest.formtest.Add(fm);      modeltest.SaveChanges();      return View(fm);    }