Hướng dẫn where do you put javascript on a razor page? - bạn đặt javascript trên trang dao cạo ở đâu?

Sử dụng phần tử giả

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
3, như được mô tả ở đây, để buộc trình biên dịch dao cạo trở lại chế độ nội dung:

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.


    // Now add markers
    @foreach (var item in Model) {
        <text>
            var markerlatLng = new google.maps.LatLng(@(Model.Latitude), @(Model.Longitude));
            var title = '@(Model.Title)';
            var description = '@(Model.Description)';
            var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'

            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });

            var marker = new google.maps.Marker({
                position: latLng,
                title: title,
                map: map,
                draggable: false
            });

            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker);
            });
        </text>
    }
</script>

Update:

Scott Guthrie gần đây đã đăng về cú pháp

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
4 trong Dao cạo, ít ỏi hơn một chút so với thẻ
<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
3 nếu bạn chỉ có một hoặc hai dòng mã JavaScript để thêm. Cách tiếp cận sau đây có thể sẽ thích hợp hơn, bởi vì nó làm giảm kích thước của HTML được tạo ra. .

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>

Đã cập nhật mã trên để làm cho cuộc gọi đến

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
6 chính xác hơn.

Để làm rõ,

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
4 buộc dao cạo trở lại chế độ văn bản, mặc dù cuộc gọi
<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
6 trông rất giống mã C#. Dao cạo sau đó chọn cú pháp
<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
9 để nói rằng nó sẽ trực tiếp xuất nội dung của các thuộc tính đó.

Cập nhật 2

Điều đáng chú ý là mã xem thực sự không phải là một nơi tốt để đặt mã JavaScript. Mã JavaScript phải được đặt trong tệp ____20 tĩnh và sau đó nó sẽ nhận được dữ liệu mà nó cần từ cuộc gọi AJAX hoặc bằng cách quét các thuộc tính

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
1 từ HTML. Bên cạnh việc làm cho nó có thể lưu trữ mã JavaScript của bạn, điều này cũng tránh được các vấn đề với mã hóa, vì dao cạo được thiết kế để mã hóa cho HTML, nhưng không phải JavaScript.

Xem mã

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}

Mã JavaScript

$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});

Giới thiệu

Các phương thức và tiện ích mở rộng AJAX trong System.web.mvc và System.web.mvc.ajax không gian tên tên tên gọi với các chế độ xem một phần JavaScript và MVC để tạo các trang web tương tác linh hoạt với mã tối thiểu. Khi sử dụng các tài nguyên này, các nhà phát triển nên nhận thức được một vài kỹ thuật cần thiết để tạo mã hiệu quả.

Các mã trong hướng dẫn này có nguồn gốc từ cùng một giải pháp Visual Studio được sử dụng cho hướng dẫn đồng hành, có sẵn trên GitHub. Bạn có thể tải xuống và chạy dự án để xem các kỹ thuật được minh họa trong hướng dẫn này trong hành động và tự mình thử nghiệm.

Một số chi tiết

Nghiên cứu trường hợp là một giải pháp Visual Studio 2017 đa dự án được phát triển từ mẫu MVC ASP.NET .NET Framework mặc định. Nó sử dụng Framework 6.1 và các mẫu thiết kế của kho lưu trữ và mô hình chế độ xem (MVVM).

Giải pháp bao gồm ba dự án tạo thành các lớp khác nhau của ứng dụng:

Dự ánLớp ứng dụng
Blip.dataBối cảnh dữ liệu và kho lưu trữ
BLIP.EntitiesThực thể dữ liệu
BLIP.WEBGiao diện người dùng (lượt xem) và logic doanh nghiệp (Bộ điều khiển)

Ứng dụng nghiên cứu trường hợp, Blipajax là một hệ thống đơn giản để thu thập, lưu trữ và truy xuất địa lý và thông tin khác về khách hàng. Nó không sẵn sàng sản xuất từ ​​các quan điểm thiết kế hoặc mã hóa; Nó tồn tại để minh họa các khái niệm được thảo luận trong hướng dẫn này. Để biết mô tả đầy đủ về giải pháp ví dụ, xem Hướng dẫn đồng hành.BlipAjax is a simple system for gathering, storing, and retrieving geographic and other information about customers. It's not production-ready from either the design or coding perspectives; it exists to illustrate the concepts discussed in this guide. For a complete description of the example solution, see the companion guide.

Tóm lại, trang khách hàng/chỉnh sửa bao gồm chế độ xem cha mẹ và ba chế độ xem một phần. Chế độ xem phần thứ ba có thể là một chế độ xem một phần để tạo địa chỉ e-mail mới hoặc chế độ xem một phần để tạo địa chỉ bưu chính mới, tùy thuộc vào giá trị được chọn trong chế độ xem một phần thứ hai. Minh họa sau đây cho thấy khách hàng/chỉnh sửa với các chú thích xác định chế độ xem (một phần), mô hình xem và hành động của bộ điều khiển (phương thức) liên quan đến việc hiển thị chế độ xem.Customer/Edit page consists of a parent view and three partial views. The third partial view can be either a partial view to create a new e-mail address or a partial view to create a new postal address, depending on the value selected in the second partial view. The following illustration shows Customer/Edit with annotations identifying the (partial) view, view model, and the controller action (method) associated with rendering the view.

Hướng dẫn where do you put javascript on a razor page? - bạn đặt javascript trên trang dao cạo ở đâu?

Trên trang Khách hàng/Chỉnh sửa, các hàm JavaScript được sử dụng để điền vào danh sách thả xuống trạng thái/khu vực với các giá trị tương ứng với giá trị được chọn trong thả xuống quốc gia. Khi người dùng thay đổi quốc gia đã chọn, các giá trị cho trường tiểu bang/khu vực phải được đặt lại.Customer/Edit page, JavaScript functions are used to populate the State/Region dropdown list with the values that correspond with the value selected in the Country dropdown. As the user changes the selected country the values for the State/Region field must be reset.

Chế độ xem một phần của JavaScript và Ajax

Có hai khía cạnh để thực hiện JavaScript với các chế độ xem dao cạo một phần của Ajax:

  1. Thư viện JavaScript cung cấp chức năng AJAX cần thiết cho các phương thức trợ giúp ASP.NET AJAX

  2. Các tập lệnh dành riêng cho triển khai cung cấp chức năng phía máy khách

Trong giải pháp ví dụ, các tập lệnh dành riêng cho triển khai là các tập lệnh có giá trị thả xuống trạng thái/khu vực.State/Region dropdown values.

Thư viện JavaScript

Việc thực hiện thành công các chế độ xem một phần AJAX phụ thuộc vào việc tải đúng một số thư viện JavaScript.

JQuery và các thư viện toàn trang web khác

Mẫu MVC ASP.NET mặc định bao gồm tệp _layout.cshtml tiêu chuẩn thực hiện các tính năng của Navigator và bao gồm các tham chiếu đến các thư viện JavaScript tiêu chuẩn. Bởi vì _layout.cshtml được bao gồm trong mọi chế độ xem trong dự án web, nên đây là một nơi tốt để bao gồm các tài liệu tham khảo tập lệnh triển khai chức năng cho các yếu tố trang, chẳng hạn như

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
2 được tìm thấy trên mỗi trang.
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
2
found included on every page.

Hầu hết các thư viện JavaScript được hiển thị ở dưới cùng của phần tử

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
3 của _layout.cshtml bằng chức năng bó MVC. Gói duy nhất được tải trong phần tử
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
4 là phiên bản 2.8.3 của Thư viện Modernizr, phiên bản hiện đại của Modernizr được bao gồm cho mục đích phát triển. Không nên bao gồm tham chiếu hiện đại trong _layout.cshtml trong mã sản xuất. Bao gồm các tài liệu tham khảo thư viện tập lệnh và tập lệnh ở cuối trang cải thiện hiệu suất kết xuất trang.
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
3
element of _Layout.cshtml using MVC bundling functionality. The only bundle loaded in the
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
4
element is version 2.8.3 of the Modernizr library, a dated version of Modernizr included for development purposes. The Modernizr reference included in _Layout.cshtml should not be included in production code. Including script library references and scripts at the end of the page improves page rendering performance.

Chức năng giao diện người dùng được cung cấp bởi Khung Bootstrap CSS được bao gồm trong thư viện bootstrap.js được tải với gói bootstrap. Bootstrap.js phụ thuộc vào thư viện jQuery phổ biến, được tải bằng gói jQuery.Bootstrap CSS framework is included in the Bootstrap.js library loaded with the Bootstrap bundle. Bootstrap.js depends on the ubiquitous jQuery library, which is loaded using the jquery bundle.

Định nghĩa của gói jQuery cho phép phiên bản jQuery hiện tại được tải mà không thay đổi định nghĩa gói hoặc _layout.cshtml để khớp với số phiên bản hiện tại. Bằng cách này, thư viện jQuery có thể được cập nhật thông qua gói NUGET được liên kết mà không cập nhật mã để giữ số phiên bản đồng bộ.jquery bundle enables the current version of jQuery to be loaded without changing the bundle definition or _Layout.cshtml to match the current version number. This way, the jQuery library can be updated through the associated NuGet package without updating the code to keep the version number in sync.

Chức năng AJAX phụ thuộc vào thư viện jQuery, nhưng không phải thư viện bootstrap. Nếu dự án web không triển khai Khung Bootstrap CSS, thư viện Bootstrap không cần thiết. Trong giải pháp ví dụ, Blipajax, Khung Bootstrap CSS, được sử dụng để cung cấp kiểu dáng và chức năng giao diện người dùng cho một số yếu tố giao diện người dùng, bao gồm các yếu tố biểu mẫu như danh sách thả xuống quốc gia và trạng thái/khu vực.jQuery library, but not the Bootstrap library. If the web project does not implement the Bootstrap CSS framework, the Bootstrap library is unnecessary. In the example solution, BlipAjax, the Bootstrap CSS framework, is used to provide user interface styling and functionality for a number of user interface elements, including form elements like the Country and State/Region dropdown lists.

_Layout.cshtml

1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>

HTML

Lưu ý rằng tệp _layout.cshtml cũng bao gồm chỉ thị dao cạo

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
5 cho phần
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
6. Điều này khiến cho bất kỳ tài liệu tham khảo và tập lệnh thư viện JavaScript bổ sung nào được tải sau gói jQuery. Thứ tự của các yếu tố này rất quan trọng để làm cho chức năng AJAX hoạt động và thứ tự tải là một lĩnh vực mà các nhà phát triển thường gặp khó khăn.
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
5
Razor directive for the
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
6
section. This causes any additional JavaScript library references and scripts to be loaded after the jQuery bundle. The order of these elements is important to getting Ajax functionality to work, and the load order is an area where developers have frequently experienced difficulty.

jQuery-validate.js, jQuery-validate-unobtrusies.js, và jQuery-unobtrious-ajax.js

Các trang bao gồm các yếu tố

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
7, chẳng hạn như khách hàng/chỉnh sửa, có thể triển khai xác thực dữ liệu phía khách hàng bằng các thư viện jQuery bổ sung và, tùy chọn, các tính năng của khung Bootstrap để tạo kiểu. Gói
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
8 tải cả hai thư viện cần thiết:
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
7
elements, such as Customer/Edit, can implement client-side data validation using additional jQuery libraries and, optionally, features of the Bootstrap framework for styling. The
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
8
bundle loads both of the required libraries:

  1. jquery-validate-unobtrusive.js

Các thư viện này được tải qua gói jQueryVal.jqueryval bundle.

Các trang bao gồm chức năng AJAX, chẳng hạn như khách hàng/chỉnh sửa cần bao gồm một thư viện JavaScript bổ sung:Customer/Edit need to include an additional JavaScript library:

jquery-unobtrusive-ajax.js

Thư viện này được tải qua gói jQueryUnobtruses.jqueryunobtrusive bundle.

Lưu ý rằng quy ước đặt tên tiêu chuẩn cho các thư viện tạo ra tiềm năng nhầm lẫn: gói jqueryunobtring không bao gồm thư viện cho AJAX không gây khó chịu và gói jqueryunobtrious không bao gồm thư viện để xác nhận không gây khó chịu.jqueryunobtrusive bundle does not include the library for unobtrusive Ajax and the jqueryunobtrusive bundle does not include the library for unobtrusive validation.

Như được hiển thị bên dưới, chế độ xem cha mẹ cho khách hàng/chỉnh sửa bao gồm chỉ thị

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
9 cho phần
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
0 được chỉ định trong _layout.cshtml. Các gói được ghi nhận ở trên được bao gồm trong phần này và, theo thứ tự của các chỉ thị trong _layout.cshtml, tải các thư viện được chỉ ra ở trên sau khi tải gói jQuery. Thứ tự này là điều cần thiết để thực hiện đúng thư viện Ajax JavaScript; Nó phụ thuộc vào jQuery.Customer/Edit includes a
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
9
directive for the
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
0
section specified in _Layout.cshtml. The bundles noted above are included in this section and, following the order of the directives in _Layout.cshtml, load the libraries indicated above after loading the jquery bundle. This order is essential to proper implementation of the Ajax JavaScript library; it depends on jQuery.

Thứ tự tải cũng rất quan trọng để thực hiện đúng các thư viện xác thực. Cả jQuery-validate.js và jQuery-validate-unobtrusius.js yêu cầu thư viện jQuery phải được tải trước.jquery-validate.js and jquery-validate-unobtrusive.js require the jQuery library to be loaded first.

Chế độ xem cha mẹ EDIT.CSHTML cũng bao gồm mã JavaScript dành riêng cho trang sẽ được mô tả chi tiết trong phần tiếp theo.Edit.cshtml parent view also includes page-specific JavaScript code which will be described in detail in the next section.

Customer/Edit.cshtml

1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}

HTML

Lưu ý rằng phía máy chủ

$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
1 được bao gồm trong các chỉ thị
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
2 cho các gói xác thực và AJAX để loại bỏ bất kỳ sự nhầm lẫn nào có thể phát sinh trên các tập lệnh nào được đưa vào các gói do quy ước đặt tên tiêu chuẩn.
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
1
are included with the
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
2
directives for the validation and Ajax bundles to eliminate any confusion that might arise over which scripts are included in the bundles as a result of the standard naming convention.

Cũng lưu ý rằng thứ tự của các chỉ thị này là không bắt buộc, nhưng vì chức năng AJAX quan trọng hơn đối với hoạt động đúng của trang so với xác thực phía máy khách, nên nên tải thư viện đó ngay sau thư viện jQuery để giảm thiểu Khả năng các lỗi tải sẽ ngăn thư viện AJAX tải. Điều này đặc biệt quan trọng khi thêm sự phức tạp của việc tải các thư viện JavaScript từ các mạng phân phối nội dung (CDN) trong sản xuất với phiên bản cục bộ của thư viện như là một dự phòng khi CDN không có sẵn.

Cuối cùng, lưu ý rằng các yếu tố

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
7 của trang khách hàng/chỉnh sửa được bao gồm trong các chế độ xem một phần, thay vì chế độ xem EDIT.CSHTML của cha mẹ. Tuy nhiên, quy ước dành cho JavaScript được liên kết với chế độ xem một phần được đặt trong tệp .cshtml cho chế độ xem cha mẹ, thay vì chế độ xem một phần mà họ áp dụng. Phần tiếp theo sẽ hiển thị quy ước này trong thực tế cũng như mô tả một ngoại lệ đáng chú ý.
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
7
elements of the Customer/Edit page are included in the partial views, rather than the parent Edit.cshtml view. Nevertheless, the convention is for JavaScript associated with a partial view to be located in the .cshtml file for the parent view, rather than the partial view to which they apply. The next section will show this convention in practice as well as describing a notable exception.

Các kịch bản cụ thể thực hiện

Trang khách hàng/chỉnh sửa bao gồm các chức năng JavaScript dành riêng cho triển khai, trang web các giá trị cho danh sách thả xuống quốc gia và tiểu bang/khu vực trong cả hai chi tiết khách hàng chỉnh sửa và thêm một phần địa chỉ bưu chính mới của trang. Như đã lưu ý ở trên, quy ước mã hóa trong ASP.NET MVC là đặt các tập lệnh cho một chế độ xem một phần trong tệp .cshtml cho chế độ xem cha mẹ (đây là một ngoại lệ quan trọng đối với quy ước này, sẽ được mô tả chi tiết bên dưới).Customer/Edit page includes implementation-specific JavaScript functions that populate the values for the Country and State/Region dropdown lists in both the Edit customer details and Add a new postal address sections of the page. As noted above, the coding convention in ASP.NET MVC is to put the scripts for a partial view in the .cshtml file for the parent view (here is one important exception to this convention, which will be described in detail below).

Thực hiện khách hàngDitPartial.cshtmlCustomerEditPartial.cshtml

Vì các yếu tố kiểm soát liên quan đến các tập lệnh được bao gồm trong chế độ xem một phần của customereditpartial.cshtml, sẽ rất hữu ích khi xem xét chế độ xem một phần khi kiểm tra chức năng của các tập lệnh.CustomerEditPartial.cshtml, it will be helpful to look at the partial view when examining the functionality of the scripts.

CustomerEditPartial.cshtml

1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
2
3@{
4    Layout = null;
5}
6
7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
8{
9    @Html.AntiForgeryToken()
10
11    <div class="form-horizontal">
12        <hr />
13        <h4>Edit customer details</h4>
14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
15        <div class="form-group">
16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
17            <div class="col-md-10">
18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
19            </div>
20        </div>
21
22        <div class="form-group">
23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
24            <div class="col-md-10">
25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
27            </div>
28        </div>
29
30        <div class="form-group">
31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
32            <div class="col-md-10">
33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
35            </div>
36        </div>
37
38        <div class="form-group">
39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
40            <div class="col-md-10">
41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
43            </div>
44        </div>
45
46        <div class="form-group">
47            <div class="col-md-offset-2 col-md-10">
48                <input type="submit" value="Save" class="btn btn-primary" />
49            </div>
50        </div>
51    </div>
52}

HTML

Lưu ý rằng phía máy chủ

$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
1 được bao gồm trong các chỉ thị
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
2 cho các gói xác thực và AJAX để loại bỏ bất kỳ sự nhầm lẫn nào có thể phát sinh trên các tập lệnh nào được đưa vào các gói do quy ước đặt tên tiêu chuẩn.
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
4
helper methods for the
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
5
and
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
6
elements.

Cũng lưu ý rằng thứ tự của các chỉ thị này là không bắt buộc, nhưng vì chức năng AJAX quan trọng hơn đối với hoạt động đúng của trang so với xác thực phía máy khách, nên nên tải thư viện đó ngay sau thư viện jQuery để giảm thiểu Khả năng các lỗi tải sẽ ngăn thư viện AJAX tải. Điều này đặc biệt quan trọng khi thêm sự phức tạp của việc tải các thư viện JavaScript từ các mạng phân phối nội dung (CDN) trong sản xuất với phiên bản cục bộ của thư viện như là một dự phòng khi CDN không có sẵn.

1@{
2    Layout = null;
3}

HTML

Cuối cùng, lưu ý rằng các yếu tố

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
7 của trang khách hàng/chỉnh sửa được bao gồm trong các chế độ xem một phần, thay vì chế độ xem EDIT.CSHTML của cha mẹ. Tuy nhiên, quy ước dành cho JavaScript được liên kết với chế độ xem một phần được đặt trong tệp .cshtml cho chế độ xem cha mẹ, thay vì chế độ xem một phần mà họ áp dụng. Phần tiếp theo sẽ hiển thị quy ước này trong thực tế cũng như mô tả một ngoại lệ đáng chú ý.CustomerEditPartial.cshtml is the first partial view loaded in the Edit.cshtml parent view and because Edit.cshtml does not have an
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
7
directive, it is necessary to tell the Razor engine not to use _Layout.cshtml for the partial view. Without this directive, the Razor engine gets confused and renders elements from the layout file, such as the footer.

Các kịch bản cụ thể thực hiệnCustomerEditPartial.cshtml

Trang khách hàng/chỉnh sửa bao gồm các chức năng JavaScript dành riêng cho triển khai, trang web các giá trị cho danh sách thả xuống quốc gia và tiểu bang/khu vực trong cả hai chi tiết khách hàng chỉnh sửa và thêm một phần địa chỉ bưu chính mới của trang. Như đã lưu ý ở trên, quy ước mã hóa trong ASP.NET MVC là đặt các tập lệnh cho một chế độ xem một phần trong tệp .cshtml cho chế độ xem cha mẹ (đây là một ngoại lệ quan trọng đối với quy ước này, sẽ được mô tả chi tiết bên dưới).Customer/Edit page is used, the customer already exists, so there is an existing record including values for the customer's Country and State/Region. Accordingly, the script needs to populate the list of values for the State/Region field with values associated with the existing value for Country and set the value of the Region control accordingly, as follows in the first of the JavaScript functions in Customer/Edit.cshtml, shown below.

Thực hiện khách hàngDitPartial.cshtml

$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
8").

Vì các yếu tố kiểm soát liên quan đến các tập lệnh được bao gồm trong chế độ xem một phần của customereditpartial.cshtml, sẽ rất hữu ích khi xem xét chế độ xem một phần khi kiểm tra chức năng của các tập lệnh.

$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
9") indicates places where the irrelevant code has been redacted for brevity.

1<script type="text/javascript">
2    $(document).ready(function () {
3        var selectedCountry = $("#Country").val();
4        var selectedRegion = $("#Region").val();
5        var regionsSelect = $('#Region');
6        AddRegions(selectedCountry, regionsSelect);
7        if (selectedRegion != null && selectedRegion != '') {
8            regionsSelect.val = selectedRegion;
9        };
10    });
11...
12</script>

HTML

Lưu ý các phương pháp trợ giúp

$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
4 cho các phần tử
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
5 và
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
6.
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
0
and
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1
elements provided by the view model CustomerEditViewModel.cs, calls the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
2
function to add the appropriate values to the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1
element, and resets the value of the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1
element.

Ngoài ra, lưu ý mã dao cạo sau:

1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
2 function calls the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
6
method to get a list of the regions for the country identified in the value for the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1
element. It then appends these key-value pairs to the list of values for the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1
element, adding a blank record before doing so to present the drop-down in an unselected state. As noted above, the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
9
function for Edit.cshtml resets the selected value for
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1
once the list is loaded.

1<script type="text/javascript">
2...
3function AddRegions(selectedCountry, regionsSelect) {
4    $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
5        if (regions != null && !jQuery.isEmptyObject(regions)) {
6            regionsSelect.append($('<option/>', {
7                value: null,
8                text: ""
9            }));
10            $.each(regions, function (index, region) {
11                regionsSelect.append($('<option/>', {
12                    value: region.Value,
13                    text: region.Text
14                }));
15            });
16        };
17    });
18</script>

HTML

Vì khách hàng đã được tải trong chế độ xem cha mẹ chỉnh sửa. Không có chỉ thị này, động cơ dao cạo bị nhầm lẫn và hiển thị các yếu tố từ tệp bố cục, chẳng hạn như chân trang.

1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
1 controller action, see the BlipAjax example solution on GitHub.

Tập lệnh cho khách hàngDitPartial.cshtml

Trường hợp sử dụng cho biểu mẫu để chỉnh sửa quốc gia và tiểu bang/khu vực được liên kết với khách hàng có phần khác so với việc thêm một địa chỉ bưu chính mới, vì vậy chức năng tập lệnh cũng có phần khác nhau. Khi khách hàng/trang chỉnh sửa được sử dụng, khách hàng đã tồn tại, do đó, có một hồ sơ hiện có bao gồm các giá trị cho quốc gia và tiểu bang/khu vực của khách hàng. Theo đó, tập lệnh cần đưa ra danh sách các giá trị cho trường Trạng thái/Vùng với các giá trị liên quan đến giá trị hiện có của quốc gia và đặt giá trị của điều khiển khu vực phù hợp, như sau trong các hàm đầu tiên của JavaScript trong Khách hàng/Chỉnh sửa. CSHTML, hiển thị dưới đây..cshtml. JavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a

1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
2 helper method, as in this section from Edit.cshtml:

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
0

HTML

Các chế độ xem một phần của customerEditPartial.cshtml và địa chỉTypePartial.cshtml cho phép "thành phần" của chế độ xem khách hàng/edit.cshtml. Cả hai chế độ xem một phần được hiển thị cùng lúc với chế độ xem cha mẹ, và do đó các phần tử

1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
0 và
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1 có sẵn để ràng buộc khi sự kiện
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
5 xảy ra.CustomerEditPartial.cshtml and AddressTypePartial.cshtml enable the "componentization" of the Customer/Edit.cshtml view. Both partial views are rendered at the same time as the parent view, and thus the
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
0
and
1<!DOCTYPE html>
2<html>
3<head>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
10</head>
11<body>
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
38
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
42</body>
43</html>
1
elements are available for binding when the
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
5
event occurs.

Các tập lệnh cho createdepostaladdresspartial.cshtmlCreatePostalAddressPartial.cshtml

Kết xuất của chế độ xem một phần CreatEpostalAddressPartial.CSHTML được bắt đầu bởi sự kiện

1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
6 của mẫu Ajax được tạo bởi Chế độ xem một phần của UnderfortypePepartial.cshtml, được định nghĩa như sau:CreatePostalAddressPartial.cshtml is initiated by the
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
6
event of the Ajax form created by the AddressTypePartial.cshtml partial view, defined as follows:

AddressTypePartial.cshtml

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
1

csharp

Mặc dù biểu mẫu Phương pháp trợ giúp

1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
7, hành động của bộ điều khiển
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
8 khởi động kết xuất chế độ xem một phần AJAX thay vì hành động
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
9 cho chế độ xem một phần của CreatePostalAddressPartial.cshtml. Chế độ xem một phần thay thế phần tử
1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
2
3@{
4    Layout = null;
5}
6
7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
8{
9    @Html.AntiForgeryToken()
10
11    <div class="form-horizontal">
12        <hr />
13        <h4>Edit customer details</h4>
14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
15        <div class="form-group">
16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
17            <div class="col-md-10">
18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
19            </div>
20        </div>
21
22        <div class="form-group">
23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
24            <div class="col-md-10">
25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
27            </div>
28        </div>
29
30        <div class="form-group">
31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
32            <div class="col-md-10">
33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
35            </div>
36        </div>
37
38        <div class="form-group">
39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
40            <div class="col-md-10">
41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
43            </div>
44        </div>
45
46        <div class="form-group">
47            <div class="col-md-offset-2 col-md-10">
48                <input type="submit" value="Save" class="btn btn-primary" />
49            </div>
50        </div>
51    </div>
52}
0 trống của EDIT.CSHTML (để biết giải thích chi tiết hơn về việc sử dụng các chế độ xem một phần AJAX, xem Hướng dẫn đồng hành).
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
7
helper method form, the controller action
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
8
kicks off the rendering of the Ajax partial view rather than an
1@*Models are in partial views.*@
2
3@section header {
4
5}
6
7@{
8    ViewBag.Title = "Edit Customer Information";
9}
10
11<div class="row">
12    <div class="col-md-12">
13        <h2>Edit Customer Information</h2>
14    </div>
15</div>
16
17<div id="EditCustomerPartial">
18    @Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
19</div>
20
21<div id="SelectAddressTypePartial">
22    @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })
23</div>
24
25<div id="CreateAddress"></div>
26
27<div class="row">
28    <div class="form-group">
29        <div class="col-md-12">
30            <hr />
31            <div>
32                @Html.ActionLink("Back to List", "Index")
33            </div>
34        </div>
35    </div>
36</div>
37
38@section Scripts {
39    @Scripts.Render("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@
40    @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@
41
42    <script type="text/javascript">
43    $(document).ready(function () {
44        var selectedCountry = $("#Country").val();
45        var selectedRegion = $("#Region").val();
46        var regionsSelect = $('#Region');
47        AddRegions(selectedCountry, regionsSelect);
48        if (selectedRegion != null && selectedRegion != '') {
49            regionsSelect.val = selectedRegion;
50        };
51    });
52
53    $("#Country").change(function () {
54        var selectedCountry = $("#Country").val();
55        var regionsSelect = $('#Region');
56        regionsSelect.empty();
57        if (selectedCountry != null && selectedCountry != '') {
58            AddRegions(selectedCountry, regionsSelect);
59        }
60    });
61
62    function AddRegions(selectedCountry, regionsSelect) {
63        $.getJSON('@Url.Action("GetRegions")', { iso3: selectedCountry }, function (regions) {
64            if (regions != null && !jQuery.isEmptyObject(regions)) {
65                regionsSelect.append($('<option/>', {
66                    value: null,
67                    text: ""
68                }));
69                $.each(regions, function (index, region) {
70                    regionsSelect.append($('<option/>', {
71                        value: region.Value,
72                        text: region.Text
73                    }));
74                });
75            };
76        });
77    }
78    </script>
79}
9
action for the CreatePostalAddressPartial.cshtml partial view. The partial view replaces the empty
1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
2
3@{
4    Layout = null;
5}
6
7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
8{
9    @Html.AntiForgeryToken()
10
11    <div class="form-horizontal">
12        <hr />
13        <h4>Edit customer details</h4>
14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
15        <div class="form-group">
16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
17            <div class="col-md-10">
18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
19            </div>
20        </div>
21
22        <div class="form-group">
23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
24            <div class="col-md-10">
25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
27            </div>
28        </div>
29
30        <div class="form-group">
31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
32            <div class="col-md-10">
33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
35            </div>
36        </div>
37
38        <div class="form-group">
39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
40            <div class="col-md-10">
41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
43            </div>
44        </div>
45
46        <div class="form-group">
47            <div class="col-md-offset-2 col-md-10">
48                <input type="submit" value="Save" class="btn btn-primary" />
49            </div>
50        </div>
51    </div>
52}
0
element of Edit.cshtml (for a more detailed explanation of using Ajax partial views, see the companion guide).

Bởi vì Chế độ xem một phần địa chỉ bưu chính không được hiển thị khi chế độ xem cha mẹ và các chế độ xem một phần trước được hiển thị, JavaScript được tải với chế độ xem cha mẹ EDIT.CSHTML không thể bị ràng buộc với các phần tử trên chế độ xem một phần địa chỉ bưu chính.Edit.cshtml cannot be bound to elements on the postal address partial view.

Theo đó, các tập lệnh liên quan đến chế độ xem một phần AJAX phải được bao gồm trong chế độ xem một phần, thay vì chế độ xem cha mẹ. Đây là một ngoại lệ chính cho quy ước mã hóa, được yêu cầu bởi ràng buộc tập lệnh.

Lưu ý rằng một số yếu tố hình thức đã được điều chỉnh lại cho sự ngắn gọn, như được hiển thị bởi một dấu chấm lửng ("

$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
9").
$('[data-marker]').each(function() {
    var markerData = $(this).data('marker');
    addMarker(markerData.Latitude, markerData.Longitude,
              markerData.Description, markerData.Title);
});
9
").

CreatePostalAddressPartial.cshtml

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>
2

HTML

Lưu ý các tính năng sau của chế độ xem một phần:

  • Phần tử

    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    2 không được đặt trong phần tập lệnh.
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    2
    element is not enclosed in a scripts section.

  • Tên của các yếu tố cho các trường quốc gia và khu vực,

    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    3 và
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    4 khác biệt với tên của các yếu tố tương tự trên chế độ xem một phần của khách hàng. Điều này rất cần thiết cho ràng buộc thích hợp: Hãy chắc chắn các yếu tố có các thuộc tính
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    5 và
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    6 riêng biệt, nếu thích hợp.
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    3
    and
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    4
    are distinct from the names of the similar elements on the CustomerEditPartial.cshtml partial view. This is essential for proper binding: be sure elements have distinct
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    5
    and
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    6
    attributes, as appropriate.

  • Sự kiện kích hoạt dân số của các giá trị cho việc thả xuống

    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    4 là sự kiện
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    8 cho phần tử
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    3.
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    4
    drop-down is the
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    8
    event for the
    1@model Blip.Entities.Customers.ViewModels.CustomerEditViewModel
    2
    3@{
    4    Layout = null;
    5}
    6
    7@using (Html.BeginForm("EditCustomerPartial", "Customer", FormMethod.Post))
    8{
    9    @Html.AntiForgeryToken()
    10
    11    <div class="form-horizontal">
    12        <hr />
    13        <h4>Edit customer details</h4>
    14        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    15        <div class="form-group">
    16            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
    17            <div class="col-md-10">
    18                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    19            </div>
    20        </div>
    21
    22        <div class="form-group">
    23            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
    24            <div class="col-md-10">
    25                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    26                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
    27            </div>
    28        </div>
    29
    30        <div class="form-group">
    31            @Html.LabelFor(model => model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    32            <div class="col-md-10">
    33                @Html.DropDownListFor(model => model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Country" })
    34                @Html.ValidationMessageFor(model => model.SelectedCountryIso3, "", new { @class = "text-danger" })
    35            </div>
    36        </div>
    37
    38        <div class="form-group">
    39            @Html.LabelFor(model => model.SelectedRegionCode, htmlAttributes: new { @class = "control-label col-md-2" })
    40            <div class="col-md-10">
    41                @Html.DropDownListFor(model => model.SelectedRegionCode, new SelectList(Model.Regions, "Value", "Text"), htmlAttributes: new { @class = "form-control", @id="Region" })
    42                @Html.ValidationMessageFor(model => model.SelectedRegionCode, "", new { @class = "text-danger" })
    43            </div>
    44        </div>
    45
    46        <div class="form-group">
    47            <div class="col-md-offset-2 col-md-10">
    48                <input type="submit" value="Save" class="btn btn-primary" />
    49            </div>
    50        </div>
    51    </div>
    52}
    3
    element.

  • Mặc dù tập lệnh được tải với chế độ xem một phần, nhưng nó có thể tham chiếu các thư viện và tập lệnh trên chế độ xem cha mẹ chỉnh sửa.cshtml, bao gồm thư viện jQuery ("
    $('[data-marker]').each(function() {
        var markerData = $(this).data('marker');
        addMarker(markerData.Latitude, markerData.Longitude,
                  markerData.Description, markerData.Title);
    });
    
    8") và hàm
    1<!DOCTYPE html>
    2<html>
    3<head>
    4    <meta charset="utf-8" />
    5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6    <title>@ViewBag.Title - My ASP.NET Application</title>
    7    @Styles.Render("~/Content/css")
    8    @Scripts.Render("~/bundles/modernizr")
    9    @RenderSection("header", required: false)
    10</head>
    11<body>
    12    <div class="navbar navbar-inverse navbar-fixed-top">
    13        <div class="container">
    14            <div class="navbar-header">
    15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    16                    <span class="icon-bar"></span>
    17                    <span class="icon-bar"></span>
    18                    <span class="icon-bar"></span>
    19                </button>
    20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    21            </div>
    22            <div class="navbar-collapse collapse">
    23                <ul class="nav navbar-nav">
    24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    25                    <li>@Html.ActionLink("About", "About", "Home")</li>
    26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    27                </ul>
    28            </div>
    29        </div>
    30    </div>
    31    <div class="container body-content">
    32        @RenderBody()
    33        <hr />
    34        <footer>
    35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
    36        </footer>
    37    </div>
    38
    39    @Scripts.Render("~/bundles/jquery")
    40    @Scripts.Render("~/bundles/bootstrap")
    41    @RenderSection("scripts", required: false)
    42</body>
    43</html>
    2.Edit.cshtml parent view, including the jQuery library ("
    $('[data-marker]').each(function() {
        var markerData = $(this).data('marker');
        addMarker(markerData.Latitude, markerData.Longitude,
                  markerData.Description, markerData.Title);
    });
    
    8
    ") and the function
    1<!DOCTYPE html>
    2<html>
    3<head>
    4    <meta charset="utf-8" />
    5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6    <title>@ViewBag.Title - My ASP.NET Application</title>
    7    @Styles.Render("~/Content/css")
    8    @Scripts.Render("~/bundles/modernizr")
    9    @RenderSection("header", required: false)
    10</head>
    11<body>
    12    <div class="navbar navbar-inverse navbar-fixed-top">
    13        <div class="container">
    14            <div class="navbar-header">
    15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    16                    <span class="icon-bar"></span>
    17                    <span class="icon-bar"></span>
    18                    <span class="icon-bar"></span>
    19                </button>
    20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    21            </div>
    22            <div class="navbar-collapse collapse">
    23                <ul class="nav navbar-nav">
    24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    25                    <li>@Html.ActionLink("About", "About", "Home")</li>
    26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    27                </ul>
    28            </div>
    29        </div>
    30    </div>
    31    <div class="container body-content">
    32        @RenderBody()
    33        <hr />
    34        <footer>
    35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
    36        </footer>
    37    </div>
    38
    39    @Scripts.Render("~/bundles/jquery")
    40    @Scripts.Render("~/bundles/bootstrap")
    41    @RenderSection("scripts", required: false)
    42</body>
    43</html>
    2
    .

Điểm cuối cùng là một điểm mạnh mẽ để sử dụng các tập lệnh tùy chỉnh với các chế độ xem một phần AJAX. Chế độ xem một phần được hiển thị với AJAX không phô trương cần bao gồm mã tập lệnh vừa đủ để chăm sóc các liên kết phần tử và các cuộc gọi đến các thư viện và chức năng trong cha mẹ, giúp ngăn chặn sự trùng lặp của mã.

Ngoài ra, lưu ý rằng xác thực phía máy khách không phô trương được tải với gói

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
8 trong chế độ xem cha mẹ sẽ hoạt động trên các phần tử biểu mẫu trong chế độ xem một phần được tải với AJAX.
@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}
8
bundle in the parent view will work on the form elements in the partial view loaded with Ajax.

Sự kết luận

Khi được cấu trúc đúng, mã JavaScript có thể mở rộng sức mạnh của các thư viện JavaScript và mã tùy chỉnh thành các chế độ xem một phần dao cạo được hiển thị với thư viện AJAX không gây khó chịu. Các bước chính là:

  • Tải jQuery trong _layout.cshtml

  • Tải jQuery-unobtrious-ajax.js, jQuery.validate.js, và jQuery.validate.unobtrusies.js trong phần

    1@{
    2    Layout = null;
    3}
    3 của các trang thích hợp
    1@{
    2    Layout = null;
    3}
    3
    section of appropriate pages

  • Bao gồm các tập lệnh cho các chế độ xem một phần được hiển thị với chế độ xem cha mẹ trong chế độ xem cha mẹ

  • Bao gồm các tập lệnh cho các chế độ xem một phần được hiển thị với AJAX trong chế độ xem một phần

  • Bao gồm các chức năng phổ biến trong phần
    1@{
    2    Layout = null;
    3}
    3 của chế độ xem cha mẹ
    1@{
    2    Layout = null;
    3}
    3
    section of the parent view

Với các kỹ thuật này, có thể tạo các trang web mạnh mẽ, tương tác, dựa trên dữ liệu với mã tối thiểu và không phải buộc dây trên chi phí phát triển của việc triển khai khung phía khách hàng.

Thêm thông tin

Nếu bạn muốn đi sâu hơn vào các chủ đề được thảo luận trong hướng dẫn này hoặc thử nghiệm mã được hiển thị ở trên, thì sau đây là danh sách các tài nguyên được chọn.

Ví dụ dự án

Giải pháp hoàn chỉnh Visual Studio được mô tả trong hướng dẫn này có sẵn trên GitHub:

Dự án ví dụ được cung cấp như là, không có bất kỳ bảo hành nào được thể hiện hoặc ngụ ý. Cả Pluralsight và tác giả đều không chịu trách nhiệm cho bất kỳ lỗi hoặc thiếu sót nào.

Các khóa học Pluralsight liên quan

ASP.NET MVC Các chủ đề nâng cao của Scott Allen, ngày 22 tháng 7 năm 2009. Mô -đun đầu tiên của khóa học này, AJAX với ASP.NET MVC cung cấp một cái nhìn tổng quan được tường thuật hay về công nghệ liên quan.

Các nguồn lực khác

learn.jquery.com - Đây là trang web chính thức cho tài liệu JQuery, được cung cấp bởi Quỹ JQuery.

Microsoft: Bundling và Minification, của Rick Anderson, ngày 23 tháng 8 năm 2012 - Đây là hướng dẫn cần thiết để thực hiện gói và thu nhỏ trong ASP.NET MVC. Nếu bạn đang viết cho các thiết bị di động-và bạn nên-Google sẽ giảm tốc độ hiệu suất trang của bạn trừ khi bạn sử dụng gói và thu nhỏ, làm tổn thương hiệu suất của bạn trong tìm kiếm.

Microsoft: System.Web.MVC không gian tên và Microsoft: System.web.mvc.ajax không gian tên - Đây là các tài liệu tham khảo tài liệu chính tắc cho lớp Ajaxhelper, AjaxExtensions (bao gồm phương thức bắt đầu) và các lớp AJAXOPTION. Lưu ý rằng nếu bạn đi tìm thông tin trên Docs.microsoft.com, nó sẽ khởi động bạn vào các URL này. Mặc dù trang này đề cập đến Visual Studio 2013, trên thực tế, tài liệu gần đây nhất.

Wikipedia: AJAX (lập trình) - Một bản tóm tắt tốt đẹp về kiến ​​trúc, lịch sử và triển khai AJAX. Nền tảng tốt cho người mới bắt đầu tìm kiếm một nền tảng cơ bản trong công nghệ.

Tôi có thể sử dụng JavaScript trong các trang dao cạo không?

Bạn có thể gọi các phương thức JavaScript từ các trang Blazor với sự trợ giúp của JavaScript interop bằng cách đưa ijsruntime phụ thuộc vào trang dao cạo.Sau đó giới thiệu tập lệnh trong trang HTML của ứng dụng Blazor.Kiểm tra liên kết này để biết thêm thông tin.. Then refer the script in the HTML page of the blazor application. Check this link for more information.

Đâu là nơi chính xác để chèn tập lệnh JavaScript?

JavaScript trong hoặc bạn có thể đặt bất kỳ số lượng tập lệnh nào trong tài liệu HTML.Các tập lệnh có thể được đặt trong hoặc trong phần của trang HTML hoặc trong cả hai. or You can place any number of scripts in an HTML document. Scripts can be placed in the , or in the section of an HTML page, or in both.

Làm thế nào bao gồm JavaScript trong CSHTML?

Chuyển đến lượt xem -> Chia sẻ -> _Layout.cshtml và thêm mã kết xuất.Đảm bảo đăng ký tệp JavaScript tùy chỉnh sau Gói jQuery vì chúng tôi sẽ sử dụng jQuery trong tệp JS của chúng tôi.Nếu không, chúng tôi sẽ gặp lỗi jQuery và cũng đăng ký điều này trước khi tập lệnh hiển thị. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.