---
# System prepended metadata

title: mod03
tags: [mvc]

---

```csharp

// overloading
public string SayHi()=> "Hi...";
[HttpPost]
public string SayHi(string username)=> $"Hi {username}";

// string
public string XmlDemo()
    => "<book><title>mvc</title><price>1000</price></book>";

// content helper
public ActionResult XmlDemo2()
{
    return Content("<book><title>mvc</title><price>1000</price></book>"
        ,"text/xml");
   
}
// json helper
public ActionResult JsonDemo()
{            
    var obj = new { id=1, Name="aaa" };
    return Json(obj, JsonRequestBehavior.AllowGet);// c# object-->json
}

//=================================
// homecontroller.cs
public ActionResult Index()
{
    ViewBag.date1=DateTime.Now;
    ViewData["date2"]=DateTime.Now;

    return View();           
}

// home/index.cshtml
<ul>
    <li>@ViewData["date1"]</li>
    <li>@ViewBag.date2</li>
</ul>

//===================================
// operacontroller.cs
public ActionResult Details(int? id)
{
    if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Opera opera=context.Operas.Find(id);

    if (opera == null) return HttpNotFound();

    return View(opera);
}

// opera/details.cshtml
@model Mod02.Models.Opera

<h1>Opera Details</h1>
<ul>
    <li>
        @Html.DisplayNameFor(m => m.Title) :
        @Html.DisplayFor(m => m.Title)
    </li>
    <li>
        @Html.DisplayNameFor(m => m.Year) :
        @Html.DisplayFor(m => m.Year)
    </li>
    <li>
        @Html.DisplayNameFor(m => m.Composer) :
        @Html.DisplayFor(m => m.Composer)
    </li>
</ul>
<p>
    @Html.ActionLink("Back to List","Index")
</p>

// opera/index.cshtml
<table border="1">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(m => m.Title)</th>
            <th>@Html.DisplayNameFor(m => m.Year)</th>
            <th>@Html.DisplayNameFor(m => m.Composer)</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@Html.DisplayFor(m => item.Title)</td>
                <td>@Html.DisplayFor(m => item.Year)</td>
                <td>@Html.DisplayFor(m => item.Composer)</td>
                <td>
                    @Html.ActionLink("Details","Details",new {id=item.OperaID})
                </td>
            </tr>
        }
    </tbody>
</table>

// home/index.cshtml
@Html.ActionLink("Opera List","Index","Opera")
//=================================
// operacontroller.cs
public ActionResult Create()
{
    return View();
}
[HttpPost]
public ActionResult Create(Opera opera)
{
    if (ModelState.IsValid)
    {
        context.Operas.Add(opera);
        context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(opera);
}

// opera/create.cshtml
@model Mod02.Models.Opera

<h1>Opera Create</h1>
@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(m => m.Title)
        @Html.EditorFor(m => m.Title)
    </div>
    <div>
        @Html.LabelFor(m => m.Year)
        @Html.EditorFor(m => m.Year)
    </div>
    <div>
        @Html.LabelFor(m => m.Composer)
        @Html.EditorFor(m => m.Composer)
    </div>
    <div>
        <input type="submit" value="Save" />
    </div>
}
<p>
    @Html.ActionLink("Back to List", "Index")
</p>

// opera/index.cshtml
 <p>
     @Html.ActionLink("Create", "Create")
 </p>
//===================================
// opera/create.cshtml
 <div>
     @Html.LabelFor(m => m.Title)
     @Html.EditorFor(m => m.Title)
     @Html.ValidationMessageFor(m => m.Title)
 </div>
 <div>
     @Html.LabelFor(m => m.Year)
     @Html.EditorFor(m => m.Year)
     @Html.ValidationMessageFor(m => m.Year)
 </div>
 <div>
     @Html.LabelFor(m => m.Composer)
     @Html.EditorFor(m => m.Composer)
     @Html.ValidationMessageFor(m => m.Composer)
 </div>

<script src="~/Scripts/jquery-3.7.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
//===========================
// opera/create.cshtml
@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    <div>
        @Html.LabelFor(m => m.Title)
        @Html.EditorFor(m => m.Title)
        @Html.ValidationMessageFor(m => m.Title, "*")
    </div>
    <div>
        @Html.LabelFor(m => m.Year)
        @Html.EditorFor(m => m.Year)
        @Html.ValidationMessageFor(m => m.Year, "*")
    </div>
    <div>
        @Html.LabelFor(m => m.Composer)
        @Html.EditorFor(m => m.Composer)
        @Html.ValidationMessageFor(m => m.Composer, "*")
    </div>
    <div>
        <input type="submit" value="Save" />
    </div>
}



// site.css
body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

/* styles for validation helpers */
.field-validation-error {
    color: #b94a48;
}

.field-validation-valid {
    display: none;
}

input.input-validation-error {
    border: 1px solid #b94a48;
}

input[type="checkbox"].input-validation-error {
    border: 0 none;
}

.validation-summary-errors {
    color: #b94a48;
}

.validation-summary-valid {
    display: none;
}
//=================================
// operacontroller.cs
public ActionResult Edit(int? id)
{
    if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Opera opera = context.Operas.Find(id);

    if (opera == null) return HttpNotFound();

    return View(opera);
}

[HttpPost]
public ActionResult Edit(Opera opera)
{
    if (ModelState.IsValid)
    {
        context.Entry(opera).State=EntityState.Modified;
        context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(opera);
}

// opera/edit.cshtml
 <h1>Opera Edit</h1>

 @using (Html.BeginForm())
 {
     @Html.HiddenFor(m=>m.OperaID)
     @Html.ValidationSummary()
     <div>
         @Html.LabelFor(m => m.Title)
         @Html.EditorFor(m => m.Title)
         @Html.ValidationMessageFor(m => m.Title, "*")
     </div>
     <div>
         @Html.LabelFor(m => m.Year)
         @Html.EditorFor(m => m.Year)
         @Html.ValidationMessageFor(m => m.Year, "*")
     </div>
     <div>
         @Html.LabelFor(m => m.Composer)
         @Html.EditorFor(m => m.Composer)
         @Html.ValidationMessageFor(m => m.Composer, "*")
     </div>
     <div>
         <input type="submit" value="Save" />
     </div>
 }
 <p>
     @Html.ActionLink("Back to List", "Index")
 </p>

// opera/index.cshtml
<tr>
    <td>@Html.DisplayFor(m => item.Title)</td>
    <td>@Html.DisplayFor(m => item.Year)</td>
    <td>@Html.DisplayFor(m => item.Composer)</td>
    <td>
        @Html.ActionLink("Details", "Details", new { id = item.OperaID })
        @Html.ActionLink("Edit", "Edit", new { id = item.OperaID })
    </td>
</tr>
//=================================
// operacontroller.cs
public ActionResult Delete(int? id)
{
    if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Opera opera = context.Operas.Find(id);

    if (opera == null) return HttpNotFound();

    return View(opera);
}
[HttpPost]
[ActionName(nameof(Delete))]
public ActionResult xxx(int? id)
{
    if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Opera opera = context.Operas.Find(id);

    if (opera == null) return HttpNotFound();

    context.Operas.Remove(opera);
    context.SaveChanges();

    return RedirectToAction(nameof(Index));
}

// opera/delete.cshtml
<h1>Opera Delete Confirm</h1>
<ul>
    <li>
        @Html.DisplayNameFor(m => m.Title) :
        @Html.DisplayFor(m => m.Title)
    </li>
    <li>
        @Html.DisplayNameFor(m => m.Year) :
        @Html.DisplayFor(m => m.Year)
    </li>
    <li>
        @Html.DisplayNameFor(m => m.Composer) :
        @Html.DisplayFor(m => m.Composer)
    </li>
</ul>
@using (Html.BeginForm())
{
    <input type="submit" value="Delete" />
}
<p>
    @Html.ActionLink("Back to List","Index")
</p>

// opera/index.cshtml
<table border="1">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(m => m.Title)</th>
            <th>@Html.DisplayNameFor(m => m.Year)</th>
            <th>@Html.DisplayNameFor(m => m.Composer)</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@Html.DisplayFor(m => item.Title)</td>
                <td>@Html.DisplayFor(m => item.Year)</td>
                <td>@Html.DisplayFor(m => item.Composer)</td>
                <td>
                    @Html.ActionLink("Details", "Details", new { id = item.OperaID })
                    @Html.ActionLink("Edit", "Edit", new { id = item.OperaID })
                   @Html.ActionLink("Delete", "Delete", new { id = item.OperaID })
                </td>
            </tr>
        }
    </tbody>
</table>
//==========================
// operacontroller.cs
public ActionResult Delete(int? id)
{
    if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Opera opera = context.Operas.Find(id);

    if (opera == null) return HttpNotFound();

    context.Operas.Remove(opera);
    context.SaveChanges();

    return RedirectToAction(nameof(Index));
}

// opera/index.cshtml
<table border="1">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(m => m.Title)</th>
            <th>@Html.DisplayNameFor(m => m.Year)</th>
            <th>@Html.DisplayNameFor(m => m.Composer)</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@Html.DisplayFor(m => item.Title)</td>
                <td>@Html.DisplayFor(m => item.Year)</td>
                <td>@Html.DisplayFor(m => item.Composer)</td>
                <td>
                    @Html.ActionLink("Details", "Details", new { id = item.OperaID })
                    @Html.ActionLink("Edit", "Edit", new { id = item.OperaID })
                    @*@Html.ActionLink("Delete", "Delete", new { id = item.OperaID })*@
                    @Html.ActionLink("Delete", "Delete", new { id = item.OperaID },
                   new {onclick="return confirm('Delete');"})

                </td>
            </tr>
        }
    </tbody>
</table>

//=====================================
//l ogcactionfilter.cs

public class LogActionFilter:ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Debug.WriteLine(nameof(OnActionExecuted));
    }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Debug.WriteLine(nameof(OnActionExecuting));
    }
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        Debug.WriteLine(nameof(OnResultExecuted));
    }
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        Debug.WriteLine(nameof(OnResultExecuting));
    }
}
// homecontroller.cs
[LogActionFilter]
public ActionResult Index()
{
    Debug.WriteLine("Home...");

    return View();      
}
//====================================
// logactionfilter.cs
public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var controller = filterContext.RouteData.Values["controller"];
        var action = filterContext.RouteData.Values["action"];
        var id = filterContext.RouteData.Values["id"];


        Debug.WriteLine($"Log: {controller}/{action}/{id} {DateTime.Now}");
    }       
}

//global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        GlobalFilters.Filters.Add(new LogActionFilter());
    }
}
//================================
//web.config
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
	  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

	<log4net>
		<root>
			<level value="DEBUG" />
			<appender-ref ref="FileAppender" />
		</root>
		<appender name="FileAppender" type="log4net.Appender.FileAppender">
			<file value="C:\Logs\MyApp.log" />
			<appendToFile value="true" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
			</layout>
		</appender>
	</log4net>
    
//global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        log4net.Config.XmlConfigurator.Configure();

//logactionfilter.cs
public class LogActionFilter : ActionFilterAttribute
{
    private static readonly ILog log = 
        LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var controller = filterContext.RouteData.Values["controller"];
        var action = filterContext.RouteData.Values["action"];
        var id = filterContext.RouteData.Values["id"];

        log.Info($"Log: {controller}/{action}/{id} {DateTime.Now}");
        //Debug.WriteLine($"Log: {controller}/{action}/{id} {DateTime.Now}");
    }       
}


```

