ハロの外部記憶インターフェイス

そろそろ覚える努力が必要かも…

Ajaxを利用して非同期更新を行う。

ASP.NET MVC5でAjaxを使おう

ポップアップで更に非同期で検索を行い結果を親画面に戻したい
なので、Ajaxを使うとします。

準備物

1.Microsoft jQuery Unobtrusive Ajax
www.nuget.org
Nugetパッケージマネージャーを利用してプロジェクトにインストールします。
※私も見落としていましたが、デフォルトではAjax機能は入っていないのです。残念

2.jQuery UI (Combined Library)
※子画面表示にjQueryUiを使っているため、必要
www.nuget.org

3.BundleConfig.csにjQuery Unobtrusive Ajaxを追加します。

bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
    "~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
    "~/Scripts/jquery.unobtrusive-ajax.js"));

4._Layout.cshtmlに追加します
 Layoutに追加しとけば、全画面に適用されるため

@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/jqueryajax")

Controller

MyActionController.cs
1.親画面用

public ViewResult Top() {
    return View();
}

2.子画面

public ViewResult Child() {
    return View();
}

3.Ajax実行用

public ActionResult AjaxSearch() {
  // Ajaxの場合のみ何かをするように制御が可能
  if (Request.IsAjaxRequest()){
    var model = new AjaxSearchViewModel():
    return PartialView("_Result", model);
  }
  else {
    var model = new AjaxSearchViewModel():
    return ResultView(model);
  }
}

View

 1.親画面ビュー
子画面リンクをクリックすると子画面(jQueryUi.Dialog)が表示され、選択されたコードをAlert表示する。
Top.cshtml

   <a href="#" id="openChild">子画面</a>
   <div id="dialogChild" style="display:none;">
            Html.Action("Child")
    </div>
<script>
$(function () {
    $('#openChild').click(function () {
        showDialog();
    });
});

//dialog
function showDialog() {
    $('#dialogChild').dialog({
        title: "子画面タイトル",
        width: 550,
        height: 400,
        modal: true,
        buttons: {
            OK: function () {
                 var selected = $('#code').val().trim());        //子画面の選択コード
                 alert("子画面のコード:" + selected);
                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () { $(this).dialog("destroy"); }
    });
}
</script>

2.子画面ビュー
Searchボタンにより、Ajax実行され、resultGridに結果が表示される。
Child.cshtml

@using (Ajax.BeginForm("AjaxSearch", new AjaxOptions() { UpdateTargetId = "resultGrid" }))
{
    <input type="submit" value="Search" />
}
<div id="resultGrid">
</div>

JavaScriptを利用する場合は

<script>
function search() {
$("#resultGrid").load('/Home/AjaxSearch');
}
</script>
<a href="#" id="search_link" onclick="search()" > </a>

呼び出しの時に、実行させるにはdialogのOpen処理で以下の様に実行することが可能

$('#dialogChild').dialog({ /// options //
    open: function(event) { $("#search_link").trigger("click"); }
   });

ダイヤログが開くタイミングで実行させることが可能になる。
3.Ajax部分ビュー
選択された行を選択状態にする。
AjaxSearch.cshtml

@model IEnumerable<App.Models.AjaxSearchViewModel>

<script>
    function Click_Row(row) {
        $("tr").css({'background-color':'white'});
        row.style.backgroundColor = '#cccccc';
        document.getElementById('code').value = row.cells.item(0).firstChild.nodeValue;
        document.getElementById('name').value = row.cells.item(1).firstChild.nodeValue;
    }
</script>

<table class="table table-striped" cellpadding="1" cellspacing="5">
    <thead>
        <tr class="ui-widget-header ">
            <th style="width:80px">
                コード
            </th>
            <th style="width:300px">
                名称
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr onclick="Click_Row(this)">
                <th scope="row">
                    @Html.DisplayFor(modelItem => item.コード)
                </th>
                <td>
                    @Html.DisplayFor(modelItem => item.名称)
                </td>
            </tr>
        }
    </tbody>

</table>