---
# System prepended metadata

title: mod10
tags: [mvc]

---

```csharp
// operascontroller.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OperaID,Title,Year,Composer")]
    Opera opera)
{
    if (ModelState.IsValid)
    {
        ViewData["message"] = "資料新增成功";
        TempData["message"] = "資料新增成功!!";
        Session["message"] = "資料新增成功!!!!";

        db.Operas.Add(opera);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(opera);
}

// operas/index.cshtml
<h2>Opera List</h2>

<ul>
    <li>ViewData: @ViewData["message"]</li>
    <li>TempData: @TempData["message"]</li>
    <li>Session: @Session["message"]</li>
</ul>
//===========================
// homeController.cs
public ActionResult SessionDemo()
{
    if (Session["count"] == null)
        Session["count"] = 0;
    else
        Session["count"] = (int)Session["count"] + 1;

    return View();
}
//==========================
// web.config
 <sessionState mode="SQLServer"
		  sqlConnectionString="server=(localdb)\mssqllocaldb;trusted_connection=true;"></sessionState>
//======================
// modeles/opera.cs
[Serializable]
public partial class Opera
{



// homecontroller.cs
public ActionResult SessionDemo()
{
    Session["opera"] = 
        new Opera { OperaID = 1, Title = "xxx", Year = 2000, Composer = "yyy" };

    if (Session["count"] == null)
        Session["count"] = 0;
    else
        Session["count"] = (int)Session["count"] + 1;

    return View();
}

// home/index.cshtml
@using MyWeb.Models
@{
    ViewBag.Title = "Home";
}

<h2>Home</h2>
@if (Session["opera"] != null)
{
    Opera opera = (Opera)Session["opera"];
    <ul>
        <li>@opera.Title</li>
        <li>@opera.Year</li>
    </ul>
}

```