zoukankan      html  css  js  c++  java
  • MVC4Model常见问题

    添加实体类模型文件

    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<Album> 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.Albums
    orderby album.Title ascending
    select 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<MvcMusicStore.Models.Album>
    @{
    ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    <p>
    @Html.ActionLink("Create New", "Create")
    </p>
    <table>
    <tr>
    <th>@Html.DisplayNameFor(model => model.Genre.Name)</th>
    <th>@Html.DisplayNameFor(model => model.Artist.Name)</th>
    <th>@Html.DisplayNameFor(model => model.Title)</th>
    <th>@Html.DisplayNameFor(model => model.Price)</th>
    <th>@Html.DisplayNameFor(model => model.AlbumArtUrl)</th>
    <th></th>
    </tr>
    @foreach (var item in Model) {
    <tr>
    <td>@Html.DisplayFor(modelItem => item.Genre.Name)</td>
    <td>@Html.DisplayFor(modelItem => item.Artist.Name)</td>
    <td>@Html.DisplayFor(modelItem => item.Title)</td>
    <td>@Html.DisplayFor(modelItem => item.Price)</td>
    <td>@Html.DisplayFor(modelItem => item.AlbumArtUrl)</td>
    <td>
    @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
    @Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
    @Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
    </td>
    </tr>
    }
    </table>

    数据库连接字符串配置

    <connectionStrings>
    <add name="MusicStoreDB"
    connectionString="data source=.\SQLEXPRESS;
    Integrated Security=SSPI;
    initial catalog=MusicStore"
    providerName="System.Data.SqlClient" />
    </connectionStrings>

    三步完成数据初始化

    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<MusicStoreDB>
    {
    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/8
    public 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);
    }

    视图页面代码

    <div class="editor-field">
    @Html.DropDownList("GenreId", String.Empty)
    @Html.ValidationMessageFor(model => model.GenreId)
    </div>

    模型与视图模型

    视图页面中可能需要来自多个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)
    
    <p>
    <input type="submit" value="Save" />
    </p>
    }

    解析后的html代码

    <form action="/storemanager/Edit/8" method="post">
    <select id="GenreId" name="GenreId">
    <option value=""></option>
    <option selected="selected" value="1">Rock</option>
    <option value="2">Jazz</option>
    </select>
    <input class="text-box single-line" id="Title" name="Title"
    type="text" value="Caravan" />
    <input class="text-box single-line" id="Price" name="Price"
    type="text" value="9.99" />
    <p>
    <input type="submit" value="Save" />
    </p>
    </form>

    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);
    }}
  • 相关阅读:
    地铁线路问题分析
    软件工程大作业(社团管理系统)-个人总结报告
    第九组_社团管理系统_原型相关文档
    北京地铁线路出行和规划
    地铁线路规划
    WC 个人项目 ( node.js 实现 )
    自我介绍 + 软工5问
    软工个人项目(Java实现)
    自我介绍+软工五问
    结对编程(前后端分离)
  • 原文地址:https://www.cnblogs.com/lujianwei/p/2955965.html
Copyright © 2011-2022 走看看