博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC4--Model常见问题
阅读量:5037 次
发布时间:2019-06-12

本文共 6175 字,大约阅读时间需要 20 分钟。

添加实体类模型文件

public class Album{public virtual int AlbumId { get; set; }public virtual int GenreId { get; set; }public virtual int ArtistId { get; set; }public virtual string Title { get; set; }public virtual decimal Price { get; set; }public virtual string AlbumArtUrl { get; set; }public virtual Genre Genre { get; set; }public virtual Artist Artist { get; set; }}
public class Artist{public virtual int ArtistId { get; set; }public virtual string Name { get; set; }}
public class Genre{public virtual int GenreId { get; set; }public virtual string Name { get; set; }public virtual string Description { get; set; }public virtual List
Albums { get; set; }}

The DbContext Class

public class MusicStoreDB : DbContext

{
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Artist> Artists { get; set; }
}

LINQ语句查询方式

var db = new MusicStoreDB();var allAlbums = from album in db.Albumsorderby album.Title ascendingselect album;

The StoreManagerController控制器

public class StoreManagerController : Controller{private MusicStoreDB db = new MusicStoreDB();//// GET: /StoreManager/public ViewResult Index(){var albums = db.Albums.Include(a => a.Genre).Include(a => a.Artist);return View(albums.ToList());}

视图VIEW中遍历数据方式

@model IEnumerable
@{ViewBag.Title = "Index";}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) {
}
@Html.DisplayNameFor(model => model.Genre.Name) @Html.DisplayNameFor(model => model.Artist.Name) @Html.DisplayNameFor(model => model.Title) @Html.DisplayNameFor(model => model.Price) @Html.DisplayNameFor(model => model.AlbumArtUrl)
@Html.DisplayFor(modelItem => item.Genre.Name) @Html.DisplayFor(modelItem => item.Artist.Name) @Html.DisplayFor(modelItem => item.Title) @Html.DisplayFor(modelItem => item.Price) @Html.DisplayFor(modelItem => item.AlbumArtUrl) @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |@Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |@Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })

数据库连接字符串配置

三步完成数据初始化

1. 实现模型类.

2. 在控制器中用脚手架视图.
3. 选择数据初始化策略。

Using Database Initializers使用数据库初始化

 

 

修改global.asax.cs文件

protected void Application_Start(){Database.SetInitializer(new MusicStoreDbInitializer());AreaRegistration.RegisterAllAreas();RegisterGlobalFilters(GlobalFilters.Filters);RegisterRoutes(RouteTable.Routes);}

Seeding a Database插入初始数据

public class MusicStoreDbInitializer: DropCreateDatabaseAlways
{protected override void Seed(MusicStoreDB context){context.Artists.Add(new Artist {Name = "Al Di Meola"});context.Genres.Add(new Genre { Name = "Jazz" });context.Albums.Add(new Album{Artist = new Artist { Name="Rush" },Genre = new Genre { Name="Rock" },Price = 9.99m,Title = "Caravan"});base.Seed(context);}}

建立一个资源编辑Album

//// GET: /StoreManager/Edit/8public ActionResult Edit(int id = 0){Album album = db.Albums.Find(id);if (album == null){return HttpNotFound();}ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);return View(album);}

视图页面代码

@Html.DropDownList("GenreId", String.Empty)@Html.ValidationMessageFor(model => model.GenreId)

模型与视图模型

视图页面中可能需要来自多个Model的信息,因此引入视图Model对页面中需要显示的信息汇总到一个模型中。

public class AlbumEditViewModel{public Album AlbumToEdit { get; set; }public SelectList Genres { get; set; }public SelectList Artists { get; set; }}

The Edit View编辑视图

@using (Html.BeginForm()) {@Html.DropDownList("GenreId", String.Empty)@Html.EditorFor(model => model.Title)@Html.EditorFor(model => model.Price)

}

解析后的html代码

 

Responding to the Edit POST Request 用POST选择器属性,执行相应的动作

//// POST: /StoreManager/Edit/8[HttpPost]public ActionResult Edit(Album album){if (ModelState.IsValid){db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}

MODEL BINDING模型绑定

只更新Model中的部分值使用模型绑定的方式

[HttpPost]public ActionResult Edit(){var album = new Album();album.Title = Request.Form["Title"];album.Price = Decimal.Parse(Request.Form["Price"]);// ... and so on ...}

Explicit Model Binding显示模型绑定

将页面传入的模型保存在UPdateModel中,出现异常直接返回页面已经选择的值。

[HttpPost]public ActionResult Edit(){var album = new Album();try{UpdateModel(album);db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}catch{ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}}

TryUpdateModel也调用模型绑定,但是不会抛出异常。TryUpdateModel并返回一个布尔- true值如果模型绑定成功,该模型是有效的,返回真,无效返回false。

[HttpPost]public ActionResult Edit(){var album = new Album();if (TryUpdateModel(album)){db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}else{ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}}

验证模型绑定是否成功

[HttpPost]public ActionResult Edit(){var album = new Album();TryUpdateModel(album);if (ModelState.IsValid){db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}else{ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}}

 

转载于:https://www.cnblogs.com/bobo41/archive/2013/04/12/3016725.html

你可能感兴趣的文章
hdu1049
查看>>
H5项目常见问题及注意事项
查看>>
索尼(SONY) SVE1512S7C 把WIN8降成WIN7图文教程
查看>>
时间模块 && time datetime
查看>>
jquery自动生成二维码
查看>>
spring回滚数据
查看>>
新浪分享API应用的开发
查看>>
美国专利
查看>>
【JavaScript】Write和Writeln的区别
查看>>
百度编辑器图片在线流量返回url改动
查看>>
我对你的期望有点过了
查看>>
微信小程序wx:key以及wx:key=" *this"详解:
查看>>
下拉框比较符
查看>>
2.2.5 因子的使用
查看>>
css选择器
查看>>
photoplus
查看>>
Python 拓展之推导式
查看>>
[Leetcode] DP-- 474. Ones and Zeroes
查看>>
80X86寄存器详解<转载>
查看>>
c# aop讲解
查看>>