ASP.NET MVC ALERT訊息做法

這是一個簡單的問題,說明如下

Step01. 在Action中設定 TempData[“message”] = “此帳號已被註冊”;

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
          var user = await UserManager.FindByNameAsync(model.UserName);

       if (user != null)
       {
            //TempData 只會被讀一次,之後就會失效
            TempData["message"] = "此帳號已被註冊";
            return View(model);
       }else
       {
            //執行註冊
            //完成後,轉頁
       }
     }
       return View(model);
}

Step02.在 _layout.cshtml 中判斷 TempData[“message”] 有沒有值,有值就出現alert

<!DOCTYPE html>
<html lang="zh-TW">
<head>
 @if (TempData["message"] != null)
{
    <script type="text/javascript">
        var message = @Html.Raw(Json.Encode(TempData["message"]));
        alert(message);
    </script>
}
</head>
<body>
   @RenderBody()
</body>
</html>

ASP.NET MVC 的 ValidateAntiForgeryToken機制

這是ASP.NET MVC 為防止 CSRF (Cross-Site Request Forgery) 跨站偽造請求的攻擊的設計,作法如下:

Step01. 在 Action 加上 [ValidateAntiForgeryToken] 標籤

[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{ 
    ...
    return View();
}

Step02. 在 cshtml 就必須要加上 @Html.AntiForgeryToken(),否則會出錯

@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
    @Html.AntiForgeryToken()
}

使用 gtag.js 增加按鈕事件

常常被客戶要求 Google Analytics 要設定按鈕事件,所以先筆記起來一下


<a class="doc-dl xls" title="下載 Excel" href="/TC/OPENDATA/Comm1_MEMBER.xls">Excel</a>
<a class="doc-dl pdf" title="下載 PDF" href="/TC/OPENDATA/Comm1_MEMBER.pdf">pdf</a>
<a class="doc-dl csv" title="下載 CSV" href="TC/OPENDATA/Comm1_MEMBER.csv">csv</a>
<a class="doc-dl xml" title="下載 XML" href="/TC/OPENDATA/Comm1_MEMBER.xml">xml</a>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=追蹤碼"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }
    gtag('js', new Date());
    gtag('config', '追蹤碼');

    function download_tracking(e) {
        var addressValue = e.toString();
        addressValue = addressValue.replace('網站domain', '');
        gtag('event', '下載', {
           'event_category': 'OpenData',
           'event_label': addressValue
    });
}
</script>

ASP.NET MVC 使用 DI Framework – Autofac

Step01. 安裝 Autofac

Step02. 安裝 Autofac.Mvc5

Step03. 在 App_Start 加入 AutofacConfig.cs

public class AutofacConfig
{
    public static void Bootstrapper()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        builder.RegisterType<TimidoColorDB>()
        .As<ITimidoColorDB>()
        .InstancePerRequest();

        var services = Assembly.Load("TimidoColor.Services");
        builder.RegisterAssemblyTypes(services).AsImplementedInterfaces();

        var helper = Assembly.Load("TimidoColor.Core");
        builder.RegisterAssemblyTypes(helper).AsImplementedInterfaces();

        builder.RegisterFilterProvider();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

Step04. Global.asax 加入 AutofacConfig.Bootstrapper();

 

protected void Application_Start()
{
    AutofacConfig.Bootstrapper();

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}