省份下拉列表
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int ProvinceId { get; set; }
public Province Province { get; set; }
}
public class Province
{
public int Id { get; set; }
public string Name { get; set; }
}
public class App2DBContext:DbContext
{
public DbSet<Province> Provinces { get; set; }
public DbSet<Student> Students { get; set; }
}
控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{
App2DBContext db = new App2DBContext();
public ActionResult CreateStudent()
{
var list = new SelectList(db.Provinces,"id","Name");
ViewBag.ProvinceId = list;
return View();
}
[HttpPost]
public ActionResult CreateStudent(Student stu)
{
if (ModelState.IsValid)
{
stu.Province = db.Provinces.Find(stu.ProvinceId);
db.Students.Add(stu);
db.SaveChanges();
//return RedirectToAction("ShowStudent", new { id = stu.Id });
}
var list = new SelectList(db.Provinces, "id", "Name");
ViewBag.ProvinceId = list;
return View();
}
}
}
视图CreateStudent
@model MvcApplication2.Models.Student
@{
ViewBag.Title = "CreateStudent";
}
<h2>CreateStudent</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProvinceId)
</div>
<div class="editor-field">
@Html.DropDownList("ProvinceId","请选择省份")
@Html.ValidationMessageFor(model => model.ProvinceId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
ShowStudent视图
@model IEnumerable<MvcApplication2.Models.Student>
@{
ViewBag.Title = "ShowStudent";
}
<h2>ShowStudent</h2>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.ProvinceId)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProvinceId)
</td>
</tr>
}
</table>