Quantcast
Channel: プログラム の個人的なメモ
Viewing all 860 articles
Browse latest View live

【トラブル】【JS】【jQuery】 tablesorter に関するトラブルあれこれ

$
0
0

■ ソートが初めの一回しか効かない

 * ソートが初めの一回しか効かず、以降、そのままの状態になってしまった。
 * 期待動作としては、クリックごとに 昇順⇔降順を繰り返してほしい

トラブルがあったコード(一部抜粋)

<script>
$(document).ready(function () {

    $.tablesorter.addParser({
        id: "select",
        is: function () {
            return false;
        },
        format: function (s, table, cell) {
            return $(cell).find('select').val();
        },
        type: "text",
    });
    
    $("#sampleTable").tablesorter({
        theme: 'blue',
        headers: {
            4: {
                sorter: 'select',
            }
        },
    });
});
</script>

原因

単なるケアレスミスだったのだが
 * tablesorter() を実行していなかった

修正後

$(document).ready(function () {
    // 以下の一行を追加
    $("#sampleTable").tablesorter();

    $.tablesorter.addParser({
    ...
修正後のフルコードは以下の関連記事を参照のこと。
http://blogs.yahoo.co.jp/dk521123/35567503.html

関連記事

表(Table)の操作について ~ tablesorter の使用 ~

http://blogs.yahoo.co.jp/dk521123/25076367.html

tablesorter を使って select box をソートする

http://blogs.yahoo.co.jp/dk521123/35567503.html

【Ajax】Ajax あれこれ

$
0
0

■ 同期処理をするには

 * 「async: false」にする
  => 戻り値も受け取れる

構文

$.ajax({
  url: './index.html', // アクセス先のURL
  async: false, // ★非同期通信を行うか★
  // ..,略...
});

参考文献

http://www.atmarkit.co.jp/ait/articles/1007/30/news110_3.html
http://tkmr.hatenablog.com/entry/2014/08/08/084755

■連続通信を防止するには

構文

var jqXhr = null;

function addItem() {
  if (jqXhr) {
    // ★通信を中断する★
    // ただしfail(), always()は実行される
    jqXhr.abort();
  }
  jqXhr = $.ajax({
    type: 'get',
    url: './index.html', // アクセス先のURL
  })
  .done(function(returnData) {
    // 通信完了後
  });
}

参考文献

http://qiita.com/nekoneko-wanwan/items/bedc0e826c0842ca0b11

関連記事

ASP.NET MVC において、 Ajax でやり取りする

http://blogs.yahoo.co.jp/dk521123/35578725.html

【ASP.NET MVC】【VB】【Ajax】ASP.NET MVC において、 Ajax でやり取りする

$
0
0

サンプル

 * トグル(Toggle) で開閉したタイミングで、サーバ(コントローラ)側とAjaxで接続するサンプル

/Controllers/DemoAjaxController.vb

Imports System.Web.Mvc

Namespace Controllers
    Public Class DemoAjaxController
        Inherits Controller

        ' GET: DemoAjax
        Function Index() As ActionResult
            Return View()
        End Function

        ' GET: DemoAjax
        Public Function ConnectByAjax(model As DemoAjaxModel) As ActionResult
            ' Threading.Thread.Sleep(2000) ' わざと遅延しテスト
            Return Json(New With {Key .isSuccess = True, .result = model.IsClose},
                        JsonRequestBehavior.AllowGet)
        End Function
    End Class
End Namespace

/Models/DemoAjaxModel.vb

Public Class DemoAjaxModel

    Private Property _IsClose As Boolean

    Public Property IsClose As Boolean
        Get
            Return Me._IsClose
        End Get
        Set(ByVal value As Boolean)
            Me._IsClose = value
        End Set
    End Property

End Class

/Views/DemoAjax/Index.vbhtml

二度押し防止 + 二度通信防止
<html>
<head>
    <meta charset="UTF-8">
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>
    <script type="text/javascript">
        var jqXhr = null;
        var allowAjax = true;
        var DemoAjaxModel = {
            isClose: false,
        };

        $(function () {
            $(".slide_btn").on("click", function () {
                if (jqXhr) {
                    // ★通信を中断する★
                    // ただしfail(), always()は実行される
                    jqXhr.abort();
                    return;
                }
                if (!allowAjax) {
                    // ★二度押し防止★
                    return;
                }
                $('#slideButton').prop('disabled', true);
                allowAjax = false;

                $(this).toggleClass("active");
                $(".slide_box").slideToggle("slow");
                DemoAjaxModel.isClose = !DemoAjaxModel.isClose;
                jqXhr = $.ajax({
                    type: 'POST',
                    url: '/DemoAjax/ConnectByAjax', // アクセス先のURL
                    data: DemoAjaxModel,
                })
                .done(function (returnData) {
                    document.getElementById("result").innerText =
                        "Success? : " + returnData.isSuccess
                        + " Result : " + returnData.result;
                    jqXhr = null;
                    allowAjax = true;
                    $('#slideButton').prop('disabled', false);
                });
            })
        });
    </script>
    <style type="text/css">
        .toggle_box{
            display:none;
            color:#fff;
            background-color:#f26c4f;
            padding:20px;
            margin-top:20px;
        }
        .btn{
            background-color:#dddddd;
            padding:10px;
        }
        .btn.active{
            background-color:#1b325f;
            padding:10px;
            color:#fff;
        }
        .btn:hover{
            cursor:pointer;
        }
        .box{
            background-color:#132343;
            width:100%;
            height:20px;
            margin-top:20px;
            margin-bottom:20px;
        }

    </style>	
</head>
<body>
    @Code
        ViewData("Title") = "IndexView"
    End Code

    <h2>Ajax Demo In ASP.NET MVC</h2>
    <div id="slideButton" class="slide_btn btn">Click Me!</div>
    <div class="slide_box toggle_box">
        <p id="result">Result : </p>
    </div>

</body>
</html>

【ASP.NET MVC】【Razor】【VB】 Razor ~ Validation / 応用編 [2] ~

$
0
0

独自のデータ検証を行う

 * 以下の2パターンを考える

 [1] 1つのプロパティに対して、独自の検証を行う
 [2] 複数プロパティをまたがった検証を行う

※今回は、[1]を扱う

■ポイント

 => ValidationAttributeを継承することにより、カスタム属性の作成する

※ただ、正規表現による検証「RegularExpressionValidator」を使用できないかを検討してみた方がいい
http://blog.shibayan.jp/entry/20110708/1310132392
http://blog.shibayan.jp/entry/20130619/1371576352
http://www.atmarkit.co.jp/fdotnet/scottgublog/20100208mvc2mvalidation/mvc2mvalidation.html
http://www.remember-the-time.xyz/2012/05/aspnet-mvc-url.html
http://d.hatena.ne.jp/fyts/20071017/validator

クライアント側でのチェックをするための環境設定

環境

 * Visual Studio : Microsoft Visual Studio Express 2015 for Web 

手順

[1] Visual Studio で [ツール]-[NuGetパッケージ マネージャー]-[パッケージ マネージャー コンソール]を選択
[2] 以下のコマンド(2つ)を入力する

Install-Package jQuery.Validation
Install-Package jQuery.Validation.Unobtrusive
https://www.nuget.org/packages/jQuery.Validation/
https://www.nuget.org/packages/jQuery.Validation.Unobtrusive/

出力画面:パッケージ マネージャー コンソール

パッケージ マネージャー コンソール ホストのバージョン 3.0.0.0

利用可能なすべての NuGet コマンドを参照するには、'get-help NuGet' を入力します。

PM> Install-Package jQuery.Validation
'.NETFramework,Version=v4.6' を対象とするプロジェクト 'WebAppli' に関して、パッケージ 'jQuery.Validation.1.14.0' の依存関係情報の収集を試行しています
DependencyBehavior 'Lowest' でパッケージ 'jQuery.Validation.1.14.0' の依存関係の解決を試行しています
パッケージ 'jQuery.Validation.1.14.0' をインストールするアクションを解決しています
パッケージ 'jQuery.Validation.1.14.0' をインストールするアクションが解決されました
パッケージ 'jQuery.Validation.1.14.0' をフォルダー 'C:\Xxxx\visual studio 2015\Projects\WebAppli\packages' に追加しています
パッケージ 'jQuery.Validation.1.14.0' をフォルダー 'C:\Xxxx\visual studio 2015\Projects\WebAppli\packages' に追加しました
パッケージ 'jQuery.Validation.1.14.0' を 'packages.config' に追加しました
'jQuery.Validation 1.14.0' が WebAppli に正常にインストールされました
PM> Install-Package jQuery.Validation.Unobtrusive
'.NETFramework,Version=v4.6' を対象とするプロジェクト 'WebAppli' に関して、パッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' の依存関係情報の収集を試行しています
DependencyBehavior 'Lowest' でパッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' の依存関係の解決を試行しています
パッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' をインストールするアクションを解決しています
パッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' をインストールするアクションが解決されました
パッケージ 'Microsoft.jQuery.Unobtrusive.Validation.2.0.20710' をフォルダー 'C:\Xxxx\visual studio 2015\Projects\WebAppli\packages' に追加しています
パッケージ 'Microsoft.jQuery.Unobtrusive.Validation.2.0.20710' をフォルダー 'C:\Xxxx\visual studio 2015\Projects\WebAppli\packages' に追加しました
パッケージ 'Microsoft.jQuery.Unobtrusive.Validation.2.0.20710' を 'packages.config' に追加しました
'Microsoft.jQuery.Unobtrusive.Validation 2.0.20710' が WebAppli に正常にインストールされました
依存関係のみが含まれるパッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' をプロジェクト 'WebAppli' に追加しています。
パッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' をフォルダー 'C:\Xxxx\visual studio 2015\Projects\WebAppli\packages' に追加しています
パッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' をフォルダー 'C:\Xxxx\visual studio 2015\Projects\WebAppli\packages' に追加しました
パッケージ 'jQuery.Validation.Unobtrusive.2.0.20710' を 'packages.config' に追加しました
'jQuery.Validation.Unobtrusive 2.0.20710' が WebAppli に正常にインストールされました
PM> 

サンプル

http://blogs.yahoo.co.jp/dk521123/35593993.html
のサンプルに、独自検証(サーバ側、クライアント側)を行う
# コントローラ「PersonController.vb」およびビュー「Result.vbhtml」に変更はないので省略。

■ カスタム属性

* NoneValidationAttribute.vb
Imports System.ComponentModel.DataAnnotations
Imports System.Globalization
Imports System.Web.Mvc

<AttributeUsage(AttributeTargets.Property, AllowMultiple:=False)>
Public Class NoneValidationAttribute : Inherits ValidationAttribute
    Implements IClientValidatable

    ' 値リストを表すプライベート変数
    Private _opts As String

    Public Sub New(ByVal opts As String)
        Me._opts = opts
        Me.ErrorMessage = "{0}は、{1}を設定しないで下さい。"
    End Sub


    '  プロパティの表示名と値リストでエラー・メッセージを整形
    Public Overrides Function FormatErrorMessage(ByVal name As String) As String
        Return String.Format(CultureInfo.CurrentCulture,
                             ErrorMessageString, name, Me._opts)
    End Function

    Public Function GetClientValidationRules(
        metadata As ModelMetadata, context As ControllerContext) As IEnumerable(Of ModelClientValidationRule) Implements IClientValidatable.GetClientValidationRules
        ' 検証ルールを準備
        Dim rule = New ModelClientValidationRule() With
        {
            .ValidationType = "enumnonevalue", ' 検証名
            .ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) ' エラー
        }
        rule.ValidationParameters("opts") = Me._opts ' 検証パラメータ
        Dim list = New List(Of ModelClientValidationRule)()
        list.Add(rule)
        Return list
    End Function

    ' サーバ側の検証
    Public Overrides Function IsValid(ByVal value As Object) As Boolean

        ' 入力値が空の場合は検証をスキップ  
        If value Is Nothing Then
            Return True
        End If

        ' Noneだったら不正
        If value.ToString().Equals("None") Then
            Return False
        End If

        Return True
    End Function
End Class

■ モデル

* PersonModel.vb
Imports System.Web.Mvc

Namespace Models
    Public Class PersonModel
        Private Property _Id As Long
        Private Property _Name As String
        Private Property _Gender As Gender

        <ComponentModel.DisplayName("ID")>
        <ComponentModel.DataAnnotations.Required(ErrorMessage:="{0}は必須です。")>
        <ComponentModel.DataAnnotations.Range(100, 10000, ErrorMessage:="{0}は{1}~{2}の間で入力してください。")>
        Public Property Id As Long
            Get
                Return Me._Id
            End Get
            Set(ByVal value As Long)
                Me._Id = value
            End Set
        End Property

        <ComponentModel.DisplayName("名前")>
        <ComponentModel.DataAnnotations.Required(ErrorMessage:="{0}は必須です。")>
        <ComponentModel.DataAnnotations.StringLength(100, ErrorMessage:="{0}は{1}文字以内で入力してください。")>
        Public Property Name As String
            Get
                Return Me._Name
            End Get
            Set(ByVal value As String)
                Me._Name = value
            End Set
        End Property

        ' ★ここに適用★
        <NoneValidation("None")>
        Public Property Gender As Gender
            Get
                Return Me._Gender
            End Get
            Set(ByVal value As Gender)
                Me._Gender = value
            End Set
        End Property
    End Class

    Public Enum Gender
        None
        Man
        Woman
    End Enum

End Namespace

■ ビュー

* Index.vbhtml
@ModelType WebAppli.Models.PersonModel
@Code
    ViewData("Title") = "View"
End Code

<script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/enumNoneValue.js")" type="text/javascript"></script>

<h2>View</h2>
@Using (Html.BeginForm(
             "Result", ' アクション名
             "Person", ' コントローラ名
             FormMethod.Post))

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(False, "", New With {.class = "text-danger"})

    @Html.LabelFor(Function(model) model.Id, htmlAttributes:=New With {.class = "control-label col-md-2"})
    @Html.EditorFor(Function(model) model.Id, New With {.htmlAttributes = New With {.class = "form-control"}})
    @Html.ValidationMessageFor(Function(model) model.Id, "*")
    @<br />

    @Html.LabelFor(Function(model) model.Name, htmlAttributes:=New With {.class = "control-label col-md-2"})
    @Html.EditorFor(Function(model) model.Name, New With {.htmlAttributes = New With {.class = "form-control"}})
    @Html.ValidationMessageFor(Function(model) model.Name, "*")
    @<br />

    @Html.EnumDropDownListFor(Function(model) model.Gender, "Please select", Nothing)
    @Html.ValidationMessageFor(Function(model) model.Gender, "*")
    @<br />

    @<input type = "submit" value="Send" Class="btn btn-default" />
End Using

■ JavaScript:クライアント側の検証

* /Scripts/enumNoneValue.js
//  インテリセンス機能を有効化
/// <reference path="jquery-1.10.2.js" />

//  enumNoneValue検証をjQuery Validationに登録
$.validator.addMethod("enumnonevalue", function (value, element, param) {

    // 入力値が空の場合は検証をスキップ
    value = $.trim(value);
    if (value === '') {
        return true;
    }

    // Noneだったら不正
    if (value === "0") {
        return false;
    }
    return true;
});

$.validator.unobtrusive.adapters.addSingleVal('enumnonevalue', 'opts');


関連記事

Razor ~入門編~

http://blogs.yahoo.co.jp/dk521123/35586581.html

Razor ~ Validation / 基本編 [1] ~

http://blogs.yahoo.co.jp/dk521123/35593993.html

Razor ~ Validation / 応用編 [2] ~

http://blogs.yahoo.co.jp/dk521123/35596847.html

Razor ~ Validation / 応用編 [3] ~

http://blogs.yahoo.co.jp/dk521123/35599883.html

【ASP.NET MVC】【Razor】【VB】 Razor ~入門編~

$
0
0

■ 条件分岐

サンプル : IF文

@Code
    Dim isTrue As Boolean = True
    Dim greeting As String = "Hello!"
End Code
@If isTrue Then
    @<p>@greeting</p>
Else
    @<p>ここにはこない</p>
End If

出力結果

Hello!

サンプル : Select Case文(Switch文)

@Code
    Dim weekday = DateTime.Now.DayOfWeek
    Dim day = weekday.ToString()
    Dim message = ""
End Code

@Select Case day
    Case "Sunday"
        message = "Off"
    Case Else
        message = "Today is " & day
End Select
<p>@message</p>

出力結果

Today is Friday

■ ループ

サンプル : FOR / FOR-EACH文

@For i As Integer = 0 To 2
    @<p>For文 : @i 回目です。</p>
Next

@Code
    Dim items As String() = {"Hello", "World", "!!"}
End Code
@For Each item In items
    @<p>For Each文 : @item</p>
Next

出力結果

For文 : 0 回目です。

For文 : 1 回目です。

For文 : 2 回目です。

For Each文 : Hello

For Each文 : World

For Each文 : !!

■ コメント文

サンプル

@* コメント *@


関連記事

Razor ~ ビュー・ヘルパー編 ~ [1]

http://blogs.yahoo.co.jp/dk521123/35592671.html

Razor ~ ビュー・ヘルパー編 ~ [2]

http://blogs.yahoo.co.jp/dk521123/35591389.html

Razor ~ Validation / 基本編 [1] ~

http://blogs.yahoo.co.jp/dk521123/35593993.html

Razor ~ Validation / 応用編 [2] ~

http://blogs.yahoo.co.jp/dk521123/35596847.html

Razor ~ Validation / 応用編 [3] ~

http://blogs.yahoo.co.jp/dk521123/35599883.html

【ASP.NET MVC】【Razor】【VB】 Razor ~ ビュー・ヘルパー編 [1] ~

$
0
0

サンプル

■ モデル

* PersonModel.vb
Namespace Models
    Public Class PersonModel
        Private Property _Id As Long
        Private Property _Name As String

        Public Property Id As Long
            Get
                Return Me._Id
            End Get
            Set(ByVal value As Long)
                Me._Id = value
            End Set
        End Property

        Public Property Name As String
            Get
                Return Me._Name
            End Get
            Set(ByVal value As String)
                Me._Name = value
            End Set
        End Property
End Namespace

■ コントローラ

* PersonController.vb
Imports System.Web.Mvc
Imports WebAppli.Models

Namespace Controllers
    Public Class PersonController
        Inherits Controller

        ' GET: Person
        Function Index() As ActionResult
            Return View()
        End Function

        ' GET: Person
        Function Result(model As PersonModel) As ActionResult
            Return View(model)
        End Function
    End Class
End Namespace

■ ビュー

* Index.vbhtml
@ModelType WebAppli.Models.PersonModel
@Code
    ViewData("Title") = "View"
End Code

<h2>View</h2>
@Using (Html.BeginForm(
                "Result", ' アクション名
                "Person", ' コントローラ名
                FormMethod.Post))
    @Html.LabelFor(Function(model) model.Id, htmlAttributes:=New With {.class = "control-label col-md-2"})
    @Html.EditorFor(Function(model) model.Id, New With {.htmlAttributes = New With {.class = "form-control"}})
    @Html.LabelFor(Function(model) model.Name, htmlAttributes:=New With {.class = "control-label col-md-2"})
    @Html.EditorFor(Function(model) model.Name, New With {.htmlAttributes = New With {.class = "form-control"}})

    @<input type = "submit" value="Send" Class="btn btn-default" />
End Using
* Result.vbhtml
@ModelType WebAppli.Models.PersonModel

@Code
    ViewData("Title") = "Edit"
End Code

<h2>Result</h2>

@Html.DisplayFor(Function(model) model.Id)<br />
<br />
@Html.EditorFor(Function(model) model.Name)<br />
<br />

■ 補足:使用したビュー・ヘルパー

 * @Html.BeginForm
 * @Html.LabelFor
 * @Html.EditorFor
 * @Html.DisplayFor


関連記事

Razor ~入門編~

http://blogs.yahoo.co.jp/dk521123/35586581.html

Razor ~ ビュー・ヘルパー編 ~ [2]

http://blogs.yahoo.co.jp/dk521123/35591389.html

【ASP.NET MVC】【Razor】【VB】 Razor ~ ビュー・ヘルパー編 [2] ~

$
0
0

はじめに

以下を扱う

 * ドロップダウンリスト(select/optionタグ)
 * ラジオボタン

サンプル

■ モデル

* PersonModel.vb
Imports System.Web.Mvc

Namespace Models
    Public Class PersonModel
        Private Property _Color As Color
        Private Property _ColorSelectListItems As IEnumerable(Of SelectListItem)
        Private Property _Gender As Gender

        Sub New()
            Me._ColorSelectListItems = New List(Of SelectListItem)
        End Sub

        Public Property Color As Color
            Get
                Return Me._Color
            End Get
            Set(ByVal value As Color)
                Me._Color = value
            End Set
        End Property

        Public Property ColorSelectListItems As IEnumerable(Of SelectListItem)
            Get
                Return Me._ColorSelectListItems
            End Get
            Set(ByVal value As IEnumerable(Of SelectListItem))
                Me._ColorSelectListItems = value
            End Set
        End Property

        Public Property Gender As Gender
            Get
                Return Me._Gender
            End Get
            Set(ByVal value As Gender)
                Me._Gender = value
            End Set
        End Property
    End Class

    Public Enum Gender
        None
        Man
        Woman
    End Enum

    Public Enum Color
        None
        Red
        Blue
        Green
        Yellow
    End Enum
End Namespace

■ コントローラ

* PersonController.vb
Imports System.Web.Mvc
Imports WebAppli.Models

Namespace Controllers
    Public Class PersonController
        Inherits Controller

        ' GET: Person
        Function Index() As ActionResult
            Dim model As PersonModel = New PersonModel()
            model.ColorSelectListItems = New List(Of SelectListItem)(New SelectListItem() {
                New SelectListItem() With {.Value = Color.Red, .Text = Color.Red.ToString()},
                New SelectListItem() With {.Value = Color.Blue, .Text = Color.Blue.ToString()},
                New SelectListItem() With {.Value = Color.Yellow, .Text = Color.Yellow.ToString()}
            })
            model.Id = Nothing
            Return View(model)
        End Function

        ' GET: Person
        Function Result(model As PersonModel) As ActionResult
            Return View(model)
        End Function
    End Class
End Namespace

■ ビュー

* Index.vbhtml
@ModelType WebAppli.Models.PersonModel
@Code
    ViewData("Title") = "View"
End Code

<h2>View</h2>
@Using (Html.BeginForm(
                "Result", ' アクション名
                "Person", ' コントローラ名
                FormMethod.Post))

    ' ドロップダウンリスト

    ' 方法1
    @Html.EnumDropDownListFor(Function(model) model.Color)
    @<br />
    ' 方法2
    @Html.DropDownListFor(Function(model) model.Color, EnumHelper.GetSelectList((GetType(Models.Color))))
    @<br />
    ' 方法3
    @Html.DropDownListFor(Function(model) model.Color, Model.ColorSelectListItems)
    @<br />

    ' ラジオボタン

    @Html.RadioButtonFor(Function(model) model.Gender, Models.Gender.None,
         htmlAttributes:=New With {.checked = "checked"})
    @Html.Label("None")@<br />
    @Html.RadioButtonFor(Function(model) model.Gender, Models.Gender.Man)
    @Html.Label("Man")@<br />
    @Html.RadioButtonFor(Function(model) model.Gender, Models.Gender.Woman)
    @Html.Label("Woman")@<br />

End Using


関連記事

Razor ~入門編~

http://blogs.yahoo.co.jp/dk521123/35586581.html

Razor ~ ビュー・ヘルパー編 ~ [1]

http://blogs.yahoo.co.jp/dk521123/35592671.html

【ASP.NET MVC】【Razor】【VB】 Razor ~ Validation / 基本編 [1] ~

$
0
0

サンプル

■ モデル

* PersonModel.vb
Imports System.Web.Mvc

Namespace Models
    Public Class PersonModel
        Private Property _Id As Long
        Private Property _Name As String
        Private Property _Gender As Gender

        <ComponentModel.DisplayName("ID")>
        <ComponentModel.DataAnnotations.Required(ErrorMessage:="{0}は必須です。")>
        <ComponentModel.DataAnnotations.Range(100, 10000, ErrorMessage:="{0}は{1}~{2}の間で入力してください。")>
        Public Property Id As Long
            Get
                Return Me._Id
            End Get
            Set(ByVal value As Long)
                Me._Id = value
            End Set
        End Property

        <ComponentModel.DisplayName("名前")>
        <ComponentModel.DataAnnotations.Required(ErrorMessage:="{0}は必須です。")>
        <ComponentModel.DataAnnotations.StringLength(100, ErrorMessage:="{0}は{1}文字以内で入力してください。")>
        Public Property Name As String
            Get
                Return Me._Name
            End Get
            Set(ByVal value As String)
                Me._Name = value
            End Set
        End Property

        Public Property Gender As Gender
            Get
                Return Me._Gender
            End Get
            Set(ByVal value As Gender)
                Me._Gender = value
            End Set
        End Property
    End Class

    Public Enum Gender
        None
        Man
        Woman
    End Enum

End Namespace

■ コントローラ

* PersonController.vb
Imports System.Web.Mvc
Imports WebAppli.Models

Namespace Controllers
    Public Class PersonController
        Inherits Controller

        ' GET: Person
        Function Index() As ActionResult
            Return View()
        End Function

        ' GET: Person
        Function Result(model As PersonModel) As ActionResult
            If ModelState.IsValid Then
                Return View(model)
            Else
                Return View("Index")
            End If

        End Function
    End Class
End Namespace

■ ビュー

* Index.vbhtml
@ModelType WebAppli.Models.PersonModel
@Code
    ViewData("Title") = "View"
End Code

<h2>View</h2>
@Using (Html.BeginForm(
             "Result", ' アクション名
             "Person", ' コントローラ名
             FormMethod.Post))

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(False, "", New With {.class = "text-danger"})

    @Html.LabelFor(Function(model) model.Id, htmlAttributes:=New With {.class = "control-label col-md-2"})
    @Html.EditorFor(Function(model) model.Id, New With {.htmlAttributes = New With {.class = "form-control"}})
    @Html.ValidationMessageFor(Function(model) model.Id, "*")
    @<br />

    @Html.LabelFor(Function(model) model.Name, htmlAttributes:=New With {.class = "control-label col-md-2"})
    @Html.EditorFor(Function(model) model.Name, New With {.htmlAttributes = New With {.class = "form-control"}})
    @Html.ValidationMessageFor(Function(model) model.Name, "*")
    @<br />

    @Html.EnumDropDownListFor(Function(model) model.Gender, "Please select", Nothing)
    @Html.ValidationMessageFor(Function(model) model.Gender, "*")
    @<br />

    @<input type = "submit" value="Send" Class="btn btn-default" />
End Using
* Result.vbhtml
@ModelType WebAppli.Models.PersonModel

@Code
    ViewData("Title") = "Result"
End Code

<h2>Result</h2>

@Html.DisplayFor(Function(model) model.Id)<br />
<br />
@Html.DisplayFor(Function(model) model.Name)<br />
<br />
@Html.DisplayFor(Function(model) model.Gender)<br />
<br />


関連記事

Razor ~入門編~

http://blogs.yahoo.co.jp/dk521123/35586581.html

Razor ~ Validation / 応用編 [2] ~

http://blogs.yahoo.co.jp/dk521123/35596847.html

【ASP.NET MVC】【Razor】【VB】 Razor ~ Validation / 応用編 [3] ~

$
0
0

はじめに

http://blogs.yahoo.co.jp/dk521123/35596847.html
の [2] を扱う

# [2] 複数プロパティをまたがった検証を行う

ポイント

 => IValidatableObject インターフェースを継承することにより、複数プロパティをまたがった検証を実装する
  (IValidatableObject インターフェースは、ASP.NET MVC 3から)

# 結構簡単に理解できる

サンプル

http://blogs.yahoo.co.jp/dk521123/35596847.html
のサンプルをベースに作成
# コントローラ、ビューに変更はないので省略。

■ モデル

* PersonModel.vb
Imports System.ComponentModel.DataAnnotations
Imports System.Web.Mvc

Namespace Models
    Public Class PersonModel : Implements IValidatableObject
        Private Property _Id As Long
        Private Property _Name As String
        Private Property _Gender As Gender

        <ComponentModel.DisplayName("ID")>
        <ComponentModel.DataAnnotations.Required(ErrorMessage:="{0}は必須です。")>
        <ComponentModel.DataAnnotations.Range(100, 10000, ErrorMessage:="{0}は{1}~{2}の間で入力してください。")>
        Public Property Id As Long
            Get
                Return Me._Id
            End Get
            Set(ByVal value As Long)
                Me._Id = value
            End Set
        End Property

        <ComponentModel.DisplayName("名前")>
        <ComponentModel.DataAnnotations.Required(ErrorMessage:="{0}は必須です。")>
        <ComponentModel.DataAnnotations.StringLength(100, ErrorMessage:="{0}は{1}文字以内で入力してください。")>
        Public Property Name As String
            Get
                Return Me._Name
            End Get
            Set(ByVal value As String)
                Me._Name = value
            End Set
        End Property

        <NoneValidation("None")>
        Public Property Gender As Gender
            Get
                Return Me._Gender
            End Get
            Set(ByVal value As Gender)
                Me._Gender = value
            End Set
        End Property

        ' ★ここに注目★
        Public Function Validate(validationContext As ValidationContext) As IEnumerable(Of ValidationResult) Implements IValidatableObject.Validate
            Dim list = New List(Of ValidationResult)()

            If "Mike".Equals(Me._Name) AndAlso Gender.Woman.Equals(Me._Gender) Then
                list.Add(New ValidationResult(
                         "Mikeで女って...", New String() {"Name"}))
            End If

            Return list
        End Function
    End Class

    Public Enum Gender
        None
        Man
        Woman
    End Enum

End Namespace


関連記事

Razor ~入門編~

http://blogs.yahoo.co.jp/dk521123/35586581.html

Razor ~ Validation / 基本編 [1] ~

http://blogs.yahoo.co.jp/dk521123/35593993.html

Razor ~ Validation / 応用編 [2] ~

http://blogs.yahoo.co.jp/dk521123/35596847.html

Razor ~ Validation / 応用編 [3] ~

http://blogs.yahoo.co.jp/dk521123/35599883.html

【Ajax】 Ajaxにおけるセキュリティ

【ASP.NET MVC】【Razor】【VB】 Razor ~ ビュー・ヘルパー編 [3] ~

$
0
0

はじめに

ドロップダウンリストの optgroup を考える

 まず、実装が、ASP.NET MVCのバージョンによって異なる。

   * ASP.NET MVC 5.2以上 : SelectListGroupを利用
http://qiita.com/rryu/items/0fdfde55a62a44f0add0
http://www.buildinsider.net/web/bookaspmvc5/040206
   * ASP.NET MVC 4 : 以下で対応?
http://www.jquery2dotnet.com/2014/01/html5-dropdownlist-optgroup-tag-in-mvc.html

【1】サンプル (ASP.NET MVC 5.2版)

モデル

HelloModel.vb
Imports System.Web.Mvc

Namespace Models
    Public Class HelloModel
        Private Property _Car As CarCompany
        Private Property _CarSelectListItems As IEnumerable(Of SelectListItem)

        Public Property Car As CarCompany
            Get
                Return Me._Car
            End Get
            Set(ByVal value As CarCompany)
                Me._Car = value
            End Set
        End Property

        Public Property CarSelectListItems As IEnumerable(Of SelectListItem)
            Get
                Return Me._CarSelectListItems
            End Get
            Set(ByVal value As IEnumerable(Of SelectListItem))
                Me._CarSelectListItems = value
            End Set
        End Property

        Public Enum CarCompany
            None
            Toyota
            Honda
            VolksWagen
        End Enum
    End Class
End Namespace

コントローラ

HelloController.vb
Imports System.Web.Mvc
Imports WebAppli.Models
Imports WebAppli.Models.HelloModel

Namespace Controllers
    Public Class HelloController
        Inherits Controller

        ' GET: Sample
        Function Index() As ActionResult
            Dim model As HelloModel = New HelloModel()

            Dim groupJp As SelectListGroup = New SelectListGroup() With {.Name = "Japan"}
            Dim groupForeign As SelectListGroup = New SelectListGroup() With {.Name = "Foreign"}

            model.CarSelectListItems = New List(Of SelectListItem)(New SelectListItem() {
                New SelectListItem() With {.Value = CarCompany.Toyota, .Text = CarCompany.Toyota.ToString(), .Group = groupJp},
                New SelectListItem() With {.Value = CarCompany.Honda, .Text = CarCompany.Honda.ToString(), .Group = groupJp},
                New SelectListItem() With {.Value = CarCompany.VolksWagen, .Text = CarCompany.VolksWagen.ToString(), .Group = groupForeign}
            })

            Return View(model)
        End Function
    End Class
End Namespace

ビュー

Index.vbhtml
@ModelType WebAppli.Models.HelloModel

<h2>View</h2>

@Using (Html.BeginForm())
@Html.DropDownListFor(Function(model) model.Car, Model.CarSelectListItems)
End Using

【1】サンプル (ASP.NET MVC 4版)

 * 表示はできたが、Selected/Disabledが効かなかった

準備:環境設定

http://blogs.yahoo.co.jp/dk521123/35596847.html
で行ったNuGetでインストールする

[1] Visual Studio で [ツール]-[NuGetパッケージ マネージャー]-[パッケージ マネージャー コンソール]を選択
[2] コマンド「Install-Package DropDownList.Optgroup.MVC」入力する
https://www.nuget.org/packages/DropDownList.Optgroup.MVC/

出力結果

PM> Install-Package DropDownList.Optgroup.MVC
'.NETFramework,Version=v4.6' を対象とするプロジェクト 'WebAppli' に関して、パッケージ 'DropDownList.Optgroup.MVC.1.0.0' の依存関係情報の収集を試行しています
DependencyBehavior 'Lowest' でパッケージ 'DropDownList.Optgroup.MVC.1.0.0' の依存関係の解決を試行しています
パッケージ 'DropDownList.Optgroup.MVC.1.0.0' をインストールするアクションを解決しています
パッケージ 'DropDownList.Optgroup.MVC.1.0.0' をインストールするアクションが解決されました
パッケージ 'DropDownList.Optgroup.MVC.1.0.0' をフォルダー 'C:\XXX\Projects\WebAppli\packages' に追加しています
パッケージ 'DropDownList.Optgroup.MVC.1.0.0' をフォルダー 'C:\XXX\Projects\WebAppli\packages' に追加しました
パッケージ 'DropDownList.Optgroup.MVC.1.0.0' を 'packages.config' に追加しました
'DropDownList.Optgroup.MVC 1.0.0' が WebAppli に正常にインストールされました
PM> 

モデル

HelloModel.vb
Imports System.Web.Mvc

Namespace Models
    Public Class HelloModel
        Private Property _Car As CarCompany
        Private Property _CarSelectListItems As IEnumerable(Of GroupedSelectListItem)

        Public Property Car As CarCompany
            Get
                Return Me._Car
            End Get
            Set(ByVal value As CarCompany)
                Me._Car = value
            End Set
        End Property
        Public Property CarSelectListItems As IEnumerable(Of GroupedSelectListItem)
            Get
                Return Me._CarSelectListItems
            End Get
            Set(ByVal value As IEnumerable(Of GroupedSelectListItem))
                Me._CarSelectListItems = value
            End Set
        End Property

        Public Enum CarCompany
            None
            Toyota
            Honda
            VolksWagen
        End Enum
    End Class
End Namespace

コントローラ

HelloController.vb
Imports System.Web.Mvc
Imports WebAppli.Models
Imports WebAppli.Models.HelloModel

Namespace Controllers
    Public Class HelloController
        Inherits Controller

        ' GET: Sample
        Function Index() As ActionResult

            Dim model As HelloModel = New HelloModel()

            model.CarSelectListItems = New List(Of GroupedSelectListItem)(New GroupedSelectListItem() {
                New GroupedSelectListItem() With {.Value = CarCompany.Toyota, .Text = CarCompany.Toyota.ToString(), .GroupName = "Japan", .GroupKey = "1"},
                New GroupedSelectListItem() With {.Value = CarCompany.Honda, .Text = CarCompany.Honda.ToString(), .GroupName = "Japan", .GroupKey = "1", .Disabled = True},
                New GroupedSelectListItem() With {.Value = CarCompany.VolksWagen, .Text = CarCompany.VolksWagen.ToString(), .GroupName = "Foreign", .GroupKey = "2", .Selected = True}
            })

            Return View(model)
        End Function
    End Class
End Namespace

ビュー

Index.vbhtml
@ModelType WebAppli.Models.HelloModel
@Code
    ViewData("Title") = "View"
End Code

<h2>View</h2>

@Using (Html.BeginForm())
@Html.DropDownGroupListFor(Function(model) model.Car, Model.CarSelectListItems)
End Using


関連記事

Razor ~入門編~

http://blogs.yahoo.co.jp/dk521123/35586581.html

Razor ~ ビュー・ヘルパー編 ~ [1]

http://blogs.yahoo.co.jp/dk521123/35592671.html

Razor ~ ビュー・ヘルパー編 ~ [2]

http://blogs.yahoo.co.jp/dk521123/35591389.html

【ASP.NET MVC】【VB】【Ajax】ASP.NET MVC において、 Ajax でやり取りする [2]

$
0
0

はじめに

http://blogs.yahoo.co.jp/dk521123/35578725.html
で、ASP.NET MVC において、 Ajax でやり取りすることを取り上げたが
他にもあったので、メモっとく。

今回、取り上げるクラス・メソッド

 * Ajax.BeginForm / AjaxOptions
 * Request.IsAjaxRequest()
 * PartialView

# Ajax.ActionLink()、callbackなどもあるが別の機会に...

前提

 * 以下のJavascriptが必要。
  + jquery.unobtrusive-ajax.js
  + MicrosoftAjax.js
  + MicrosoftMvcAjax.js

  => なかったら、以下の環境設定を行う

準備:環境設定

http://blogs.yahoo.co.jp/dk521123/35596847.html
で行ったNuGetでインストールする

[1] Visual Studio で [ツール]-[NuGetパッケージ マネージャー]-[パッケージ マネージャー コンソール]を選択
[2] 以下のコマンドを入力する

Install-Package Microsoft.jQuery.Unobtrusive.Ajax
Install-Package MicrosoftMvcAjax.Mvc5
https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/
https://www.nuget.org/packages/MicrosoftMvcAjax.Mvc5/
※ Request.IsAjaxRequest()からFalseが返ってくる(つまり、ajaxになってない)。
http://suusanex.hatenablog.jp/entry/2014/09/03/121509

サンプル

モデル

DemoAjaxModel.vb
Public Class DemoAjaxModel
    Private Property _Id As Integer
    Private Property _Name As String

    Public Property Id As Integer
        Get
            Return Me._Id
        End Get
        Set(ByVal value As Integer)
            Me._Id = value
        End Set
    End Property

    Public Property Name As String
        Get
            Return Me._Name
        End Get
        Set(ByVal value As String)
            Me._Name = value
        End Set
    End Property

End Class

ビュー

* SampleView.vbhtml
@Code
    ViewData("Title") = "SampleView"
End Code

<h2>SampleView</h2>
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="~/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="~/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

@Using Ajax.BeginForm("Search",
    New AjaxOptions With {
        .HttpMethod = "POST",
        .UpdateTargetId = "result"})
    @Html.TextBox("Id", "")
    @<input type = "submit" value="Search" />
End Using

<!--部分更新の結果を表示するための領域を確保-->
<div id="result"></div>
* _PartialPage1.vbhtml
<table border="1">
    <tr>
        <td>
            <ul>
                <li>@Html.Encode(Model.Id)</li>
                <li>@Html.Encode(Model.Name)</li>
            </ul>
        </td>
    </tr>
</table>

コントローラ

* DemoAjaxController.vb
Imports System.Web.Mvc

Namespace Controllers
    Public Class DemoAjaxController
        Inherits Controller

        Function SampleView() As ActionResult
            Return View()
        End Function

        Public Function Search(model As DemoAjaxModel) As ActionResult
            ' リクエストがAjax通信(非同期通信)である場合値を返す
            If Request.IsAjaxRequest() Then
                Select Case model.Id
                    Case 1
                        model.Name = "Mike"
                    Case 2
                        model.Name = "Tom"
                    Case Else
                        model.Name = "None"
                End Select
                Return PartialView("_PartialPage1", model)
            Else
                ' リクエストがAjax通信以外の場合、何もしない
                Return New EmptyResult()

            End If

        End Function

    End Class
End Namespace


関連記事

ASP.NET MVC において、 Ajax でやり取りする [1]

http://blogs.yahoo.co.jp/dk521123/35578725.html

ASP.NET MVC において、 Ajax でやり取りする [2]

http://blogs.yahoo.co.jp/dk521123/35611906.html

【JavaScript】 JavaScript で、Booleanに変換した際の注意事項

$
0
0

はじめに

 * JavaScriptにおいて、文字列から、Boolean に変換した際に、new Boolean(【文字列】)で変換していた。
   ただ、以下のケースで意図した動きにならなかったので、メモ。

(個人的に)意図した動きにならなかったケース

var boolValue = new Boolean("false"); // boolValue = true
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Boolean
より抜粋

値が省略された場合や、値が 0, -0, null, false, NaN, undefined あるいは空文字列 ("") であった場合、
オブジェクトは false の初期値を持ちます。
それ以外のあらゆる値は、オブジェクトや "false" という文字列も含めて、true の初期値を持つオブジェクトを生成
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

解決方法

 * 調べてみたけど、結局、独自に実装するしかないかと。。。

構文

targetValue == "true";

サンプル

* 「True」「False」にも対応
<!DOCTYPE html>
<html>
<body>
<div id="booleanValue1"></div>
<br>
<div id="booleanValue2"></div>
<div id="booleanValue3"></div>
<div id="booleanValue4"></div>
<div id="booleanValue5"></div>
<script type="text/javascript">
var booleanValue1 = new Boolean("false"); // booleanValue1 = true
var booleanValue2 = parseBoolean("false"); // booleanValue2 = false
var booleanValue3 = parseBoolean("False"); // booleanValue3 = false
var booleanValue4 = parseBoolean("true"); // booleanValue4 = true
var booleanValue5 = parseBoolean("True"); // booleanValue5 = true

document.getElementById("booleanValue1").innerHTML = 'booleanValue1 = new Boolean("false"); => ' + booleanValue1;
document.getElementById("booleanValue2").innerHTML = 'booleanValue2 = new Boolean("false"); => ' + booleanValue2;
document.getElementById("booleanValue3").innerHTML = 'booleanValue3 = new Boolean("False"); => ' + booleanValue3;
document.getElementById("booleanValue4").innerHTML = 'booleanValue4 = new Boolean("true"); => ' + booleanValue4;
document.getElementById("booleanValue5").innerHTML = 'booleanValue5 = new Boolean("True"); => ' + booleanValue5;

function parseBoolean(targetValue) {
   if (!targetValue) {
      return false;
   }
   
   return (targetValue.toLowerCase()) == "true";
}
</script>
</body>
</html>

出力結果

booleanValue1 = new Boolean("false"); => true

booleanValue2 = new Boolean("false"); => false
booleanValue3 = new Boolean("False"); => false
booleanValue4 = new Boolean("true"); => true
booleanValue5 = new Boolean("True"); => true

【JavaScript】 JavaScript で、コールバック関数を実装する

$
0
0

サンプル

<!DOCTYPE html>
<html>
<body>
<div id="resultMessage"></div>
<script type="text/javascript">
var sayHello = function(id, message){
   document.getElementById(id).innerText = message;
};


function callingMethod(callbackMethod, id, message){
    callbackMethod(id, message);
};

callingMethod(sayHello, 'resultMessage', 'Hello World!');
</script>
</body>
</html>

出力結果

Hello World!

【ASP.NET MVC】【C3.js】ASP.NET MVC で、 C3.jsと連携して縦棒グラフを描画するには...

$
0
0

サンプル

モデル

* ChartModel.vb
Public Class ChartModel
    Public Property XValues As Object()
    Public Property YValues As Object()
End Class

コントローラ

* ChartController.vb
Imports System.Web.Mvc

Namespace Controllers
    Public Class ChartController
        Inherits Controller

        ' GET: Chart
        Function Index() As ActionResult
            Dim model As ChartModel = New ChartModel()
            model.XValues = New Object() {"x", "English", "Math", "Science"}
            model.YValues = New Object() {"Score", 76, 87, 45}
            Return View(model)
        End Function
    End Class
End Namespace

ビュー

* Index.vbhtml
@ModelType WebAppli.ChartModel
@Code
    ViewData("Title") = "Index"
End Code

<h2>Index</h2>
<div id="chart"></div>

<link href="@Url.Content("~/Content/c3.css")" rel="stylesheet" type="text/css" />
<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
<script src="@Url.Content("~/Scripts/c3.js")" type="text/javascript"></script>
<script type="text/javascript">
    var xValues = @Html.Raw(Function(model) model.Dataset);
    var yValues = @Html.Raw(Function(model) model.YValues);
    showChart(xValues, yValues);

    function showChart(xValues, yValues) {
        var chart = c3.generate({
            bindto: '#chartToDrow',
            data: {
                x: 'x',
                columns: [
                  xValues,
                  yValues,
                ],
                type: 'bar',
            },
            grid: {
                y: {
                    lines: [{value:0}]
                }
            },
            axis: {
                x: {
                    type: 'category',
                    tick: {
                        multiline: false,
                        rotate: 75,
                    },
                    height: 130
                }
            },
        });
    }
</script>

関連記事

C3.js ~ 基本グラフのサンプル編 ~

http://blogs.yahoo.co.jp/dk521123/35514061.html

C3.js ~ C3.jsあれこれ ~

http://blogs.yahoo.co.jp/dk521123/35527809.html

【ASP.NET MVC】【VB】 Razor / VB.NET で、 JavaScriptの描画 をサーバ側で切り替えるには...

$
0
0

Razor / VB.NET で、 JavaScriptの描画 をサーバ側で切り替えるには...

 * Razor / VB.NET で、 ビューに記載しているJavaScriptをサーバ側で動的に切り替える方法を記載する。

解決策

 * 方法は2つある。(個人的には、「解決策2:@<text>」でいいと思う)
* 解決策1:@:
@If Model.IsOn Then
    @:<script type="text/javascript">
    @:  document.getElementById("result").innerText = "Hello!";
    @:</script>
Else
    @:<script type="text/javascript">
    @:  document.getElementById("result").innerText = "Good morning!";
    @:</script>
End If
* 解決策2:@<text>
@If Model.IsOn Then
    @<text>
    <script type="text/javascript">
      document.getElementById("result").innerText = "Hello!";
    </script>
    </text>
Else
    @<text>
    <script type="text/javascript">
      document.getElementById("result").innerText = "Good morning!";
    </script>
    </text>
End If

補足

外部JSのインポートもできる
@If Model.IsOn Then
    @<text>
    <script src="http://d3js.org/d3.v3.js"></script>
    <script type="text/javascript">
       // ・・・略・・・
    </script>
    </text>
End If
「@:」「@<text>」の文法の説明は以下を参照のこと
http://blogs.yahoo.co.jp/dk521123/35586581.html

サンプル

モデル

* SampleJavaScriptModel.vb
Public Class SampleJavaScriptModel
    Public Property IsOn As Boolean
End Class

コントローラ

* SampleJavaScriptController.vb
Imports System.Web.Mvc

Public Class SampleJavaScriptController
    Inherits Controller

    ' GET: SampleJavaScript
    Function Index() As ActionResult
        Dim model = New SampleJavaScriptModel()
        model.IsOn = True
        Return View(model)
    End Function
End Class

ビュー

[1] Index.vbhtml
@ModelType WebAppli.SampleJavaScriptModel
@Code
    ViewData("Title") = "Index"
End Code

<h2>Index</h2>
<div id="result"></div>
@If Model.IsOn Then
    @:<script type="text/javascript">
    @:  document.getElementById("result").innerText = "Hello!";
    @:</script>
Else
    @:<script type="text/javascript">
    @:  document.getElementById("result").innerText = "Good morning!";
    @:</script>
End If
<h2>Index</h2>
[2] Index.vbhtml
@ModelType WebAppli.SampleJavaScriptModel
@Code
    ViewData("Title") = "Index"
End Code

<h2>Index</h2>
<div id="result"></div>
@If Model.IsOn Then
    @<text>
    <script type="text/javascript">
      document.getElementById("result").innerText = "Hello!";
    </script>
    </text>
Else
    @<text>
    <script type="text/javascript">
      document.getElementById("result").innerText = "Good morning!";
    </script>
    </text>
End If
<h2>Index</h2>

出力結果

* model.IsOn = True の場合
Index

Hello!
 
Index
* model.IsOn = False の場合
Index

Good morning!
 
Index


関連記事

Razor ~入門編~

http://blogs.yahoo.co.jp/dk521123/35586581.html

【トラブル】【ASP.NET MVC】「System.Web.WebPages.StartPage から継承しません」が表示

$
0
0

はじめに

 * ASP.NET MVC でブラウザ表示しようとしたら、以下のエラー内容が表示されてしまった

エラー内容

'/' アプリケーションでサーバー エラーが発生しました。


型 'ASP._Page__ViewStart_vbhtml' は 'System.Web.WebPages.StartPage' から継承しません。 
  説明: 現在の Web 要求を実行中に、ハンドルされていない例外が発生しました。エラーに関する詳細および例外の発生場所については、スタック トレースを参照してください。 

 例外の詳細: System.Web.HttpException: 型 'ASP._Page__ViewStart_vbhtml' は 'System.Web.WebPages.StartPage' から継承しません。

ソース エラー: 


現在の Web 要求の実行中にハンドルされていない例外が生成されました。障害の原因および発生場所に関する情報については、下の例外スタック トレースを使って確認できます。  

スタック トレース: 



[HttpException (0x80004005): 型 'ASP._Page__ViewStart_vbhtml' は 'System.Web.WebPages.StartPage' から継承しません。]
   System.Web.UI.Util.CheckAssignableType(Type baseType, Type type) +9722547
   System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +66
   System.Web.WebPages.BuildManagerWrapper.CreateInstanceOfType(String virtualPath) +223
   System.Web.WebPages.VirtualPathFactoryExtensions.CreateInstance(IVirtualPathFactory factory, String virtualPath) +147
   System.Web.WebPages.VirtualPathFactoryManager.CreateInstanceOfType(String virtualPath) +152
   System.Web.WebPages.VirtualPathFactoryExtensions.CreateInstance(IVirtualPathFactory factory, String virtualPath) +74
   System.Web.WebPages.StartPage.GetStartPage(WebPageRenderingBase page, IVirtualPathFactory virtualPathFactory, String appDomainAppVirtualPath, String fileName, IEnumerable`1 supportedExtensions) +143
   System.Web.WebPages.StartPage.GetStartPage(WebPageRenderingBase page, String fileName, IEnumerable`1 supportedExtensions) +121
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +178
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

解決策

* Web.config を以下のように修正したら直った

修正前

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<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" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
・・・略・・・

修正後

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<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" />
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>
    <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

【VB.NET】Tuple(タプル)

$
0
0

サンプル

Public Class SampleTuple
    Shared Sub Main()
        Dim tuple1 = Tuple.Create("Mike", 42, Date.Now)

        Console.WriteLine(tuple1.Item1)
        Console.WriteLine(tuple1.Item2)
        Console.WriteLine(tuple1.Item3)

        Dim tuple2 As Tuple(Of String, Integer, Date) _
          = Tuple.Create("Tom", 15, Date.Now)

        Console.WriteLine(tuple2.Item1)
        Console.WriteLine(tuple2.Item2)
        Console.WriteLine(tuple2.Item3)

        Dim tuple3 = New Tuple(Of String, Integer, Date) _
            ("Sam", 27, Date.Now)
        Console.WriteLine(tuple3.Item1)
        Console.WriteLine(tuple3.Item2)
        Console.WriteLine(tuple3.Item3)
    End Sub
End Class


関連記事

【C#】Tuple(タプル)

http://blogs.yahoo.co.jp/dk521123/23249027.html

【ASP.NET MVC】 Html.AntiForgeryToken() / ValidateAntiForgeryToken

$
0
0

目的

 * CSRF(Cross-Site Request Forgeries:クロスサイト・リクエスト・フォージェリ;リクエスト強要)攻撃を
   防ぐために使用

使用方法

[1] 対象となるビュー・スクリプトにHtml.AntiForgeryTokenメソッドを埋め込む。
~~~
@Html.AntiForgeryToken()
~~~

[2] コントローラ側のアクションにValidateAntiForgeryToken属性を付与する
~~~
<ValidateAntiForgeryToken()> _
Function Xxxx(ByVal model As XxxModel) As ActionResult
  ' ・・・中略・・・
End Function
~~~

補足1:しくみについて

 1) Html.AntiForgeryTokenメソッドは、隠しフィールドを出力するとともに、
  「__RequestVerificationToken_Lw__」のような名前のクッキーを発行する(「ワンタイム・トークン」と呼んでいる)
~~~
<input name="__RequestVerificationToken" type="hidden" value="tJVYeJUMiD8s9HmKuzFESe4qHadxDC0HxD/wezi2kgK+cy/jVfzKJhEJy" />
~~~

 2) アクション・メソッド側で、このトークンの存在をチェックして、入力元のページが妥当であるかどうかを判断する

補足2:Ajax通信について

 * 上記のように実装にしてるだけだと実現できない。
http://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken
http://stackoverflow.com/questions/14473597/include-antiforgerytoken-in-ajax-post-asp-net-mvc
http://stackoverflow.com/questions/2906754/how-can-i-supply-an-antiforgerytoken-when-posting-json-data-using-ajax
http://stackoverflow.com/questions/19788916/how-to-make-ajax-request-with-anti-forgery-token-in-mvc

【ASP.NET MVC】【C3.js】ASP.NET MVC で、 C3.jsと連携してグラフを描画するには... [2]

$
0
0

はじめに

http://blogs.yahoo.co.jp/dk521123/35626537.html
では、Ajaxでやったが、コントローラ側でやる方法を記載する
http://note.chiebukuro.yahoo.co.jp/detail/n159238
が参考になった。

サンプル

http://blogs.yahoo.co.jp/dk521123/35514061.html
の「例2 : 折れ線グラフ」を題材にする

モデル

Imports System.Web.Script.Serialization

Public Class JsonModel
    Public Property ChartData As String
End Class

Public Class SampleChartModel
    Inherits BaseChartModel
    Public Property XValues As New List(Of String)
    Public Property Y1Values As New List(Of String)
    Public Property Y2Values As New List(Of String)

    Public Sub New()
        Me.XValues = New List(Of String)
        Me.Y1Values = New List(Of String)
        Me.Y2Values = New List(Of String)
    End Sub
End Class

Public MustInherit Class BaseChartModel

    Public Function ToJson() As String
        Dim serializer = New JavaScriptSerializer()
        Return serializer.Serialize(Me)
    End Function
End Class

コントローラ

* ChartController.vb
Imports System.Web.Mvc

Namespace Controllers
    Public Class ChartController
        Inherits Controller

        Function SampleChart() As ActionResult
            Dim chartModel = New SampleChartModel With
                {
                .XValues = New List(Of String) From {"x", "2015/10/30", "2015/10/31", "2015/11/01", "2015/11/02", "2015/11/03", "2015/11/04"},
                .Y1Values = New List(Of String) From {"data1", "30", "200", "100", "400", "150", "250"},
                .Y2Values = New List(Of String) From {"data2", "130", "340", "200", "500", "250", "350"}
                }

            Dim model = New JsonModel With
                {
                .ChartData = chartModel.ToJson()
                }
            Return View(model)
        End Function
    End Class
End Namespace

ビュー

* ChartController.vb
@Code
    ViewData("Title") = "SampleChart"
End Code

<h2>SampleChart</h2>
<div id="chart"></div>
<link href="@Url.Content("~/Content/c3.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>
<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
<script src="@Url.Content("~/Scripts/c3.js")" type="text/javascript"></script>
<script>
var dataset = @Html.Raw(Model.ChartData)

c3.generate({
    data: {
        x: 'x',
        xFormat: '%Y/%m/%d', // 'xFormat' can be used as custom format of 'x'
        columns: [
            dataset.XValues,
            dataset.Y1Values,
            dataset.Y2Values,
        ]
    },
    axis: {
        x: {
            type: 'timeseries',
            tick: {
                rotate: 45,
                format: '%Y/%m/%d'
            }
        }
    }
});

関連記事

ASP.NET MVC で、 C3.jsと連携してグラフを描画するには... [1]

http://blogs.yahoo.co.jp/dk521123/35626537.html

C3.js ~ 基本グラフのサンプル編 ~

http://blogs.yahoo.co.jp/dk521123/35514061.html
Viewing all 860 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>