Using Partial View to Load Partial HTML Asynchronously on the Client Side

Page updated :

Environment

Visual Studio
  • Visual Studio 2019
ASP.NET Core
  • 3.1

About adding dynamic HTML elements

When you add HTML elements dynamically, you typically add them in Javascript, for example. Because it is handled independently of the Web server side, it may be necessary to manage it in double, such as attribute values.

ASP.NET Core uses Partial View. You can retrieve HTML with server processing added to the partial HTML (.cshtml) defined on the server side. On the client side, this HTML is retrieved and an element is added to the specified location.

What's in the sample?

Defines a <ul><li> list of as a partial view.

The part of Server Partial shows the partial view defined in index.cstml. Therefore, it is expanded when the view is received from the server.

The Part of the Client Load Ajax Partial is a T:System.Web.HTML control immediately after the client retrieves the HTML and displays it on the screen. Retrieves and displays a partial view from the server in Javascript.

The button Ajax Partial is used when you press a button. Retrieves and displays a partial view from the server in Javascript. The process is the same as Load. It also describes the error handling if it is not possible to load once.

Controllers (HomeController.cs)

Defines the actions for partial views to load at load time and partial views to load when the button is pressed.

To return a partial PartialView view, call the method and return. You can also bind the model to PartialView, so List<string> we're binding here. You can define which types are actually bound on the view side, which is exactly the same as Razor syntax, such as index.cstml.

Specifying the view name is the same as for other view functions.

public class HomeController : Controller
{
  // :
  // :

  public IActionResult PartialLoad()
  {
    var list = new List<string>() { "Load1", "Load2", "Load3" };

    // PartialView を呼ぶこと
    return PartialView("Partial", list);
  }

  public IActionResult PartialButton()
  {
    var list = new List<string>() { "Button1", "Button2", "Button3" };

    // PartialView を呼ぶこと
    return PartialView("Partial", list);
  }
}

Partial View (Views/Home/Partial.cshtml)

Define a partial view in Partial.cshtml. The content is just a list of bound strings li arranged by tag. It's exactly the same as a normal view, so don't be particularly careful. Because it's Razor syntax, it's also possible to embed code in C

The file name and folder hierarchy of a partial view can be placed anywhere according to the view's alignment law.

@model List<string>

<ul>
  @foreach (var item in Model)
  {
    <li>@item</li>
  }
</ul>

Views (HTML) (Views/Home/index.cstml)

Although it is the definition of the HTML side, there are few places to explain because the display part is basically the majority.

For the part of Server Partial, you can specify the partial tag . You can expand the specified partial view. name Specify the view name for , and model specify the binding parameters for . This is similar to the PartialView method on the controller side. By the way, this is a server-side deployment process, so the client has already deployed it when it receives THE HTML.

Client Load Ajax Partial and Button Ajax Partial Button Ajax Partial deploy asynchronously retrieved partial views to div tags. On the button side, we have placed a button that specifies a button that can be successfully retrieved and an action that does not exist on purpose.

<h3>Server Partial</h3>
<p>
  リクエスト後のレスポンス HTML 時点で部分ビューが展開されている。
</p>
<partial name="Partial" model="@(new List<string>() { "Server1", "Server2", "Server3" })" />

<h3>Client Load Ajax Partial</h3>
<p>
  画面表示後に自動的にビューが読み込まれる。<br />
  Web ブラウザのデバッガのブレークポイントでスクリプトの処理を止めれば
  表示のタイミングでは読み込まれていないことは確認できる。
</p>
<div id="load_area">読み込み中…。</div>

<h3>Button Ajax Partial</h3>
<p>ボタンを押すとビューが読み込まれる</p>
<button type="button" id="button1" class="btn btn-primary">Partial View 読み込み (正常)</button>
<button type="button" id="button2" class="btn btn-danger">Partial View 読み込み (エラー)</button>
<div id="message"></div>
<div id="button_area"></div>

Views (Javascript) (Views/Home/index.cstml)

Javascript describes what to do after the initial display and what to do when the button is pressed.

Call the function on the jQuery object and call the load M:System.Data.DataQuery.GetQuery(System.Object) method. You can get a partial view asynchronously by specifying the target action (URL) as the first argument. If the retrieved content is HTML, it can be embedded as HTML inside the jQuery object.

The second argument can be a callback function, which allows you to refer to the retrieved status, etc. It is possible to branch the process depending on whether the obtained result is normal or error.

This function can be replaced with a function or function, but it load get does a little ajax more.

$(document).ready(function () {

  // 画面表示後のタイミングで読み込む
  $("#load_area").load("/Home/PartialLoad");

  // ボタンを押したときに読み込む
  $("#button1").click(function () {
    // 存在するアクションを指定
    loadPartialView('/Home/PartialButton');
  });
  $("#button2").click(function () {
    // 存在しないアクションを指定
    loadPartialView('/Home/PartialButton_xxxxxxxx');
  });
});

// 指定したパスの partial view を読み込む
function loadPartialView(loadPath) {
  $("#button_area").text('読み込み中…。');
  $("#button_area").load(loadPath, function (response, status, xhr) {
  // status === 'error' ならエラーと判断
  if (status === 'error') {
    $('#message').text('エラー (status : ' + xhr.status + ', statusText : ' + xhr.statusText + ')');
  } else {
    $('#message').text('正常 (status : ' + xhr.status + ', statusText : ' + xhr.statusText + ')');
  }
});