2014年9月14日 星期日

ASP.NET MVC (Model, View, Controller 簡單範例)

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Album
    {
        public int AlbumID { get; set; }
        public string Title { get; set; }
    }
}

List Controller

public ActionResult Index()
        {
            List albums = new List();
            albums.Add(new Album { AlbumID = 1, Title = "Sting" });
            albums.Add(new Album { AlbumID = 2, Title = "Joan" });
            return View(albums);
        }

List View

@model IEnumerable<WebApplication1.Models.Album>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </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>

Detail Controller

public ActionResult Details(int id)
        {
            var album = new Album { AlbumID = id, Title = "Hello" };
            return View(album);
        }

Detail View

@model WebApplication1.Models.Album

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Album</h4>
 <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Title)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Title)
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.AlbumID }) |
    @Html.ActionLink("Back to List", "Index")
</p>

沒有留言:

張貼留言