创建一个类Model
public class Student
{
public int Id { get; set; }
[Display(Name = "姓名")]
public string Name { get; set; }
public string SClass { get; set; }
public string IconPath { get; set; }
}
数据上下文类
public class Context:DbContext
{
public DbSet<Student> Students { get; set; }
}
创建一个控制器
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication3.Models;
namespace MvcApplication3.Controllers
{
public class HomeController : Controller
{
Context db = new Context();
public ActionResult Index()
{
return View();
}
public ActionResult UploadIcon()
{
return View();
}
//
// GET: /Home/
[HttpPost]
public ActionResult UploadIcon(HttpPostedFileBase file)
{
if (file == null)
{
return Content("没有文件!", "text/plain");
}
var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
try
{
file.SaveAs(fileName);
var stu = db.Students.Find(1);
stu.IconPath = "/upload/" + Path.GetFileName(file.FileName);
db.Entry(stu).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("ShowStudent", new { id = 1 });
}
catch
{
return Content("上传异常!", "text/plain");
}
}
public ActionResult ShowStudent(int id)
{
var stu = db.Students.Find(id);
return View(stu);
}
}
}
Index视图
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.ActionLink("上传头像", "UploadIcon");
ShowStudent视图
@model MvcApplication3.Models.Student
@{
ViewBag.Title = "ShowStudent";
}
<h2>ShowStudent</h2>
<fieldset>
<legend>Student</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.SClass)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.SClass)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.IconPath)
</div>
<div class="display-label">
<img src="@Model.IconPath"/>
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
UploadIcon视图
@{
ViewBag.Title = "UploadIcon";
}
<h2>UploadIcon</h2>
@using(Html.BeginForm("UploadIcon","Home",FormMethod.Post,new{enctype="multipart/form-data"}))
{
@Html.TextBox("file","",new{type="file",size="25"})
<input type="submit"/>
}
记得新建一个文件夹upload