0% found this document useful (0 votes)
11 views

Using JavaScript With Ajax and Razor Partial Views - Pluralsight - Pluralsight

Uploaded by

blevblayne92
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Using JavaScript With Ajax and Razor Partial Views - Pluralsight - Pluralsight

Uploaded by

blevblayne92
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

Get started Log in

ASP.NET MVC - Using


A.J. Saulsberry JavaScript with Ajax
and Razor Partial
Views
A.J. Saulsberry
Sep 6, 2019 • 29 Min read • 380,366 Views

Sep 6, 2019 • 29 Min read • 380,366 Views

Web Development ASP.NET MVC

Introduction
Introduction
Ajax helper methods and extensions in the
471

Introduction System.Web.Mvc and


Some Details System.Web.Mvc.Ajax namespaces can be
JavaScript and Ajax combined with JavaScript and MVC partial
Partial Views
views to create flexible interactive web
JavaScript Libraries
Implementation- pages with minimal code. When using
specific Scripts these resources, developers should be
Conclusion
aware of a few techniques necessary to
More Information
create
Top We use cookies to make interactions with
effective code.
our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 1/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

This guide shows how to effectively


implement JavaScript functionality when
creating a web page from Razor partial
views, including <form> elements created
using the Ajax.BeginForm helper method.
This guide is a companion to ASP.NET
MVC - Using Ajax Helpers with Razor
Partial Views.

The codes in this guide are derived from


the same Visual Studio solution used for
the companion guide, available on GitHub.
You can download and run the project to
see the techniques illustrated in this guide
in action and to experiment on your own.

Some Details
The case study is a multi-project Visual
Studio 2017 solution developed from the
default ASP.NET .NET Framework MVC
template. It uses Entity Framework 6.1 and
the repository and Model View ViewModel
(MVVM) design patterns.

The solution consists of three projects that


constitute the different layers of the
application:

We use cookies to make interactions with


our websites and services easy andProject Application Layer
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 2/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

Project Application Layer

Data Context and


Blip.Data
Repositories

Blip.Entities Data Entities

User Interface (views) and


Blip.Web
Business Logic (controllers)

The case study application, 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.

In summary, The 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)

We use cookies to make interactions with


view, view model, and the controller
our websites and services easy and
meaningful. For more informationaction
about the(method) associated
Disable cookies with
Accept cookies rendering
and close this message
cookies we use or to find out how you can
disable cookies, click here. the view.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 3/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

On the 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.

JavaScript and Ajax Partial


Views
There are two aspects to the
implementation of JavaScript with Ajax
partial Razor views:
We use cookies to make interactions with
our websites and services easy and1. JavaScript libraries that provide the
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how youAjax
can functionality needed by the
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 4/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

ASP.NET Ajax helper methods


2. Implementation-specific scripts that
provide client-side functionality

In the example solution, the


implementation-specific scripts are those
that populate the State/Region dropdown
values.

JavaScript Libraries

Successful implementation of Ajax partial


views depends on properly loading a
number of JavaScript libraries.

jQuery and Other Site-wide Libraries

The default ASP.NET MVC template


includes a standard _Layout.cshtml file
that implements navigator features and
includes references to standard JavaScript
libraries. Because _Layout.cshtml is
included in every view in the web project,
it is a good place to include script
references that implement functionality for
page elements, such as the navbar found
included on every page.

Most of the JavaScript libraries are


rendered at the bottom of the <body>
element
We use cookies to make interactions with of _Layout.cshtml using MVC
our websites and services easy and
meaningful. For more informationbundling functionality.
about the Disable cookies Thecookies
Accept onlyand
bundle
close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 5/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

loaded in the <head> 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.

The user interface functionality provided


by the 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.

The definition of the 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.

Ajax functionality depends on the jQuery


library, but not the Bootstrap library. If the
web project does not implement the
Bootstrap
We use cookies to make interactions with CSS framework, the Bootstrap
our websites and services easy and
meaningful. For more informationlibrary
about theisDisable
unnecessary.
cookies In the
Accept example
cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 6/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

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

html
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8" />
5 <meta name="viewport" content="width=d
6 <title>@ViewBag.Title - My ASP.NET App
7 @Styles.Render("~/Content/css")
8 @Scripts.Render("~/bundles/modernizr")
9 @RenderSection("header", required: fal
10 </head>
11 <body>
12 <div class="navbar navbar-inverse navb
13 <div class="container">
14 <div class="navbar-header">
15 <button type="button" clas
16 <span class="icon-bar"
17 <span class="icon-bar"
18 <span class="icon-bar"
19 </button>
20 @Html.ActionLink("Applicat
21 </div>
22 <div class="navbar-collapse co
23 <ul class="nav navbar-nav"
24 <li>@Html.ActionLink("
25 <li>@Html.ActionLink("
26 <li>@Html.ActionLink("
27 </ul>
28 </div>
29 </div>
30 </div>
We use cookies to make interactions 31
with <div class="container body-content">
our websites and services easy and 32 @RenderBody()
meaningful. For more information about the Disable cookies Accept cookies and close this message
33can
cookies we use or to find out how you <hr />
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 7/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

34 <footer>
35 <p>@DateTime.Now.Year - My ASP
36 </footer>
37 </div>
38
39 @Scripts.Render("~/bundles/jquery")
40 @Scripts.Render("~/bundles/bootstrap")
41 @RenderSection("scripts", required: fa
42 </body>
43 </html>

Note that the _Layout.cshtml file also


includes a @RenderSection Razor
directive for the "scripts" 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-
unobtrusive.js, and jquery-unobtrusive-
ajax.js

Pages that include <form> 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
jqueryval bundle loads both of the
required libraries:
We use cookies to make interactions with
our websites and services easy and
meaningful. For more information 1. jquery-validate.js
about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
2. jquery-validate-unobtrusive.js
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 8/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

These libraries are loaded through the


jqueryval bundle.

Pages that include Ajax functionality, such


as Customer/Edit need to include an
additional JavaScript library:

jquery-unobtrusive-ajax.js

This library is loaded through the


jqueryunobtrusive bundle.

Note that the standard naming convention


for the libraries creates the potential for
confusion: the jqueryunobtrusive bundle
does not include the library for
unobtrusive Ajax and the
jqueryunobtrusive bundle does not
include the library for unobtrusive
validation.

As shown below, the parent view for


Customer/Edit includes a @section
directive for the scripts 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;
We use cookies to make interactions with it depends on jQuery.
our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 9/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

The load order is also important to proper


implementation of the validation libraries.
Both jquery-validate.js and jquery-
validate-unobtrusive.js require the jQuery
library to be loaded first.

The Edit.cshtml parent view also includes


page-specific JavaScript code which will
be described in detail in the next section.

Customer/Edit.cshtml

html
1 @*Models are in partial views.*@
2
3 @section header {
4
5 }
6
7 @{
8 ViewBag.Title = "Edit Customer Informa
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", ne
19 </div>
20
21 <div id="SelectAddressTypePartial">
22 @Html.Action("AddressTypePartial", new
23 </div>
24
25 <div id="CreateAddress"></div>
26
We use cookies to make interactions 27
with <div class="row">
our websites and services easy and 28 <div class="form-group">
meaningful. For more information about the Disable cookies Accept cookies and close this message
29
cookies we use or to find out how you can <div class="col-md-12">
disable cookies, click here. 30 <hr />
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 10/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

31 <div>
32 @Html.ActionLink("Back to
33 </div>
34 </div>
35 </div>
36 </div>
37
38 @section Scripts {
39 @Scripts.Render("~/bundles/jqueryunobt
40 @Scripts.Render("~/bundles/jqueryval")
41
42 <script type="text/javascript">
43 $(document).ready(function () {
44 var selectedCountry = $("#Country"
45 var selectedRegion = $("#Region")
46 var regionsSelect = $('#Region');
47 AddRegions(selectedCountry, region
48 if (selectedRegion != null && sele
49 regionsSelect.val = selectedRe
50 };
51 });
52
53 $("#Country").change(function () {
54 var selectedCountry = $("#Country"
55 var regionsSelect = $('#Region');
56 regionsSelect.empty();
57 if (selectedCountry != null && sel
58 AddRegions(selectedCountry, re
59 }
60 });
61
62 function AddRegions(selectedCountry, r
63 $.getJSON('@Url.Action("GetRegions
64 if (regions != null && !jQuery
65 regionsSelect.append($('<o
66 value: null,
67 text: ""
68 }));
69 $.each(regions, function (
70 regionsSelect.append($
71 value: region.Valu
72 text: region.Text
73 }));
We use cookies to make interactions 74
with });
our websites and services easy and
75 the Disable cookies };Accept cookies and close this message
meaningful. For more information about
cookies we use or to find out how you
76can });
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 11/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

77 }
78 </script>
79 }

Note that server-side @*comments*@ are


included with the @Scripts.Render
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.

Also note that the order of these


directives is not mandatory, but since the
Ajax functionality is more critical to the
proper functioning of the page than the
client-side validation, it is a good idea to
load that library immediately after the
jQuery library to minimize the likelihood
that load errors would prevent the Ajax
library from loading. This is particularly
important when adding the complexity of
loading JavaScript libraries from content
delivery networks (CDN's) in production
with a local version of the library as a
fallback when the CDN is unavailable.

Finally, note that the <form> elements of


the Customer/Edit page are included in
the partial views, rather than the parent
We use cookies to make interactions with
Edit.cshtml view. Nevertheless, the
our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out howconvention
you can is for JavaScript associated
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 12/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

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.

Implementation-specific
Scripts
The 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).

Implementation of
CustomerEditPartial.cshtml

Since the control elements related to the


scripts are included in the partial view
CustomerEditPartial.cshtml, it will be
helpful
We use cookies to make interactions with to look at the partial view when
our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
examining the functionality
cookies we use or to find out how you can
of the scripts.
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 13/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

CustomerEditPartial.cshtml

html
1 @model Blip.Entities.Customers.ViewModels
2
3 @{
4 Layout = null;
5 }
6
7 @using (Html.BeginForm("EditCustomerPartia
8 {
9 @Html.AntiForgeryToken()
10
11 <div class="form-horizontal">
12 <hr />
13 <h4>Edit customer details</h4>
14 @Html.ValidationSummary(true, "",
15 <div class="form-group">
16 @Html.LabelFor(model => model
17 <div class="col-md-10">
18 @Html.EditorFor(model => m
19 </div>
20 </div>
21
22 <div class="form-group">
23 @Html.LabelFor(model => model
24 <div class="col-md-10">
25 @Html.EditorFor(model => m
26 @Html.ValidationMessageFor
27 </div>
28 </div>
29
30 <div class="form-group">
31 @Html.LabelFor(model => model
32 <div class="col-md-10">
33 @Html.DropDownListFor(mode
34 @Html.ValidationMessageFor
35 </div>
36 </div>
37
38 <div class="form-group">
39 @Html.LabelFor(model => model
40 <div class="col-md-10">
We use cookies to make interactions 41
with @Html.DropDownListFor(mode
our websites and services easy and
42 the Disable cookies Accept
meaningful. For more information about @Html.ValidationMessageFor
cookies and close this message
cookies we use or to find out how you
43can </div>
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 14/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

44 </div>
45
46 <div class="form-group">
47 <div class="col-md-offset-2 co
48 <input type="submit" value
49 </div>
50 </div>
51 </div>
52 }

Note the @Html.DropDownListFor helper


methods for the @id="Country" and
@id="Region" elements.

Also, note the following Razor code:

html
1 @{
2 Layout = null;
3 }

Because CustomerEditPartial.cshtml is the


first partial view loaded in the Edit.cshtml
parent view and because Edit.cshtml does
not have an @Model 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.

Scripts for CustomerEditPartial.cshtml

The use case for the form for editing the


We use cookies to make interactions with
Country and State/Region associated with
our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out howthe customer is somewhat different from
you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 15/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

that of adding a new postal address, so


the script functionality is also somewhat
different. When the 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.

Note that the implementation-specific


JavaScript uses the jQuery library (" $ ").

Ellipsis (" ... ") indicates places where the


irrelevant code has been redacted for
brevity.

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

We use cookies to make interactions with


our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 16/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

This function gets the value of the


Country and Region elements provided
by the view model
CustomerEditViewModel.cs, calls the
AddRegions function to add the
appropriate values to the Region element,
and resets the value of the Region
element.

The AddRegions function calls the


CustomerController.GetRegions method
to get a list of the regions for the country
identified in the value for the Region
element. It then appends these key-value
pairs to the list of values for the Region
element, adding a blank record before
doing so to present the drop-down in an
unselected state. As noted above, the
(document).ready function for
Edit.cshtml resets the selected value for
Region once the list is loaded.

html
1 <script type="text/javascript">
2 ...
3 function AddRegions(selectedCountry, regio
4 $.getJSON('@Url.Action("GetRegions")',
5 if (regions != null && !jQuery.isE
6 regionsSelect.append($('<optio
7 value: null,
8 text: ""
9 }));
10 $.each(regions, function (inde
11 regionsSelect.append($('<o
We use cookies to make interactions with
our websites and services easy and 12 value: region.Value,
meaningful. For more information about
13 the Disable cookies Accept text:
cookiesregion.Text
and close this message
cookies we use or to find out how you can
disable cookies, click here. 14 }));
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 17/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

15 });
16 };
17 });
18 </script>

For more information on the GetRegions


controller action, see the BlipAjax example
solution on GitHub.

A Note About Script Binding for Partial


Views

As noted above, the convention for


JavaScript associated with Razor partial
views is to include them in the parent view
.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
@Html.Action helper method, as in this
section from Edit.cshtml:

html
1 ...
2 <div id="EditCustomerPartial">
3 @Html.Action("EditCustomerPartial", new
4 </div>
5 ...

The partial views


CustomerEditPartial.cshtml and
AddressTypePartial.cshtml
We use cookies to make interactions with enable the
our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
"componentization" of
cookies we use or to find out how you can
the
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 18/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

Customer/Edit.cshtml view. Both partial


views are rendered at the same time as
the parent view, and thus the Country
and Region elements are available for
binding when the document.ready event
occurs.

Scripts for
CreatePostalAddressPartial.cshtml

Rendering of the partial view


CreatePostalAddressPartial.cshtml is
initiated by the HttpPost event of the
Ajax form created by the
AddressTypePartial.cshtml partial view,
defined as follows:

AddressTypePartial.cshtml

csharp
1 @model Blip.Entities.Customers.ViewModels.A
2
3 @using (Ajax.BeginForm("AddressTypePartial"
4 {
5 @Html.AntiForgeryToken()
6 ...
7 }

Despite the Html.BeginForm helper


method form, the controller action
CustomerController.AddressTypePartial
(AddressTypeViewModel model) kicks off
the rendering of the Ajax partial view
We use cookies to make interactions with
rather than an HttpGet action for the
our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out howCreatePostalAddressPartial.cshtml
you can partial
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 19/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

view. The partial view replaces the empty


<div id="CreateAddress"></div>
element of Edit.cshtml (for a more
detailed explanation of using Ajax partial
views, see the companion guide).

Because the postal address partial view is


not rendered when the parent view and
the preceding partial views are rendered,
JavaScript loaded with the parent view
Edit.cshtml cannot be bound to elements
on the postal address partial view.

Accordingly, the scripts associated with


the Ajax partial view must be included
with the partial view, rather than the
parent view. This is a key exception to
the coding convention, necessitated by
script binding.

Note that some of the form elements have


been redacted for brevity, as shown by an
ellipsis (" ... ").

CreatePostalAddressPartial.cshtml

html
1 @model Blip.Entities.Customers.ViewModels
2
3 <script type="text/javascript">
4 $("#AddressCountry").change(function (
5 var selectedCountry = $("#AddressC
6 var regionsSelect = $("#AddressReg
7 regionsSelect.empty();
We use cookies to make interactions with
8 if (selectedCountry != null && sel
our websites and services easy and
9 the Disable cookies AddRegions(selectedCountry,
meaningful. For more information about re
Accept cookies and close this message
cookies we use or to find out how you
10can }
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 20/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

11 });
12 </script>
13
14 @using (Html.BeginForm("CreatePostalAddres
15 {
16 @Html.AntiForgeryToken()
17
18 <div class="form-horizontal">
19 <hr />
20 <h4>Add a new postal address</h4>
21 @Html.ValidationSummary(true, "",
22 @Html.HiddenFor(model => model.Cus
23 <div class="form-group">
24 @Html.LabelFor(model => model
25 <div class="col-md-10">
26 @Html.EditorFor(model => m
27 </div>
28 </div>
29 ...
30 <div class="form-group">
31 @Html.LabelFor(model => Model
32 <div class="col-md-5">
33 @Html.DropDownListFor(mode
34 @Html.ValidationMessageFor
35 </div>
36 </div>
37 <div class="form-group">
38 @Html.LabelFor(model => Model
39 <div class="col-md-5">
40 @Html.DropDownListFor(mode
41 @Html.ValidationMessageFor
42 </div>
43 </div>
44
45 <div class="form-group">
46 <div class="col-md-offset-2 co
47 <input type="submit" value
48 </div>
49 </div>
50 </div>
51 }

We use cookies to make interactions with


our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 21/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

Note the following features of the partial


view:

The <script> element is not enclosed


in a scripts section.
The names of the elements for the
country and region fields,
AddressCountry and AddressRegion
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 id and
name attributes, as appropriate.
The event that triggers population of
the values for the AddressRegion drop-
down is the .change event for the
AddressCountry element.
Although the script is loaded with the
partial view, it can reference the
libraries and scripts on the Edit.cshtml
parent view, including the jQuery library
(" $ ") and the function AddRegions .

The final point is a powerful one for using


custom scripts with Ajax partial views. The
partial view rendered with unobtrusive
Ajax needs to include just enough script
code to take care of element binding and
calls to libraries and functions in the
parent, helping to prevent duplication of
code.

Also, note that the unobtrusive client-side


validation
We use cookies to make interactions with loaded with the jqueryval
our websites and services easy and
meaningful. For more informationbundle
about the in the cookies
Disable parent Accept
view cookies
will work onthis
and close themessage
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 22/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

form elements in the partial view loaded


with Ajax.

Conclusion
When structured properly, JavaScript
code can extend the power of JavaScript
libraries and custom code to Razor partial
views rendered with the unobtrusive Ajax
library. The key steps are:

Load jQuery in _Layout.cshtml


Load jquery-unobtrusive-ajax.js,
jquery.validate.js, and
jquery.validate.unobtrusive.js in the
Scripts section of appropriate pages
Include scripts for partial views
rendered with the parent view in the
parent view
Include scripts for partial views
rendered with Ajax in the partial view
Include common functions in the
Scripts section of the parent view

With these techniques, it's possible to


create powerful, interactive, data-driven
web pages with minimal code and without
having to strap on the development
overhead of implementing a client-side
framework.

We use cookies to make interactions with


our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here. More Information
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 23/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

If you want to dive deeper into the topics


discussed in this guide or experiment with
the code shown above, the following is a
selected list of resources.

Example Project

The complete Visual Studio solution


described in this guide is available on
GitHub:

BlipAjax

The example project is provided as is,


without any warranty expressed or
implied. Neither PluralSight nor the author
is responsible for any errors or omissions.

Related PluralSight Courses

ASP.NET MVC Advanced Topics by Scott


Allen, 22 July 2009. The first module of
this course, Ajax with ASP.NET MVC
provides a nice narrated overview of the
related technology.

Other Resources

learn.jquery.com — This is the official site


for jQuery documentation, provided by
the jQuery Foundation.

Microsoft: Bundling and Minification, by


Rick Anderson, 23 August 2012 — This is
We use cookies to make interactions with
our websites and services easy and
the essential guide toAccept
meaningful. For more information about the Disable cookies
implementing
cookies and close this message
cookies we use or to find out how you can
disable cookies, click here. bundling and minification in ASP.NET MVC.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 24/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

If you are writing for mobile devices – and


you should be – Google will down-rate
your page performance unless you use
bundling and minification, hurting your
performance in search.

Microsoft: System.Web.Mvc namespace,


and Microsoft: System.Web.Mvc.Ajax
namespace — These are the canonical
documentation references for the
AjaxHelper class, AjaxExtensions
(including the BeginForm method), and
AjaxOptions classes. Note that if you go
looking for information on
docs.microsoft.com it will boot you over to
these URLs. Although this page refers to
Visual Studio 2013 it is, in fact, the most
recent documentation.

Wikipedia: Ajax (programming) — A nice


summary of the Ajax architecture, history,
and implementation. Good background for
beginners looking for a fundamental
grounding in the technology.

471

We use cookies to make interactions with


our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can LEARN MORE
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 25/26
8/19/2020 Using JavaScript with Ajax and Razor partial views | Pluralsight | Pluralsight

(/offer/2020/33-off-q3)

PERSONAL ANNUAL AND PREMIUM


We use cookies to make interactions with our websites and services easy and meaningful. For more information
about the cookies we use or to find out how you can disable cookies, click here (/privacy).
SUBSCRIPTIONS -
ACCEPT COOKIES AND CLOSE THIS
STARTS NOW MESSAGE

Disable cookies

We use cookies to make interactions with


our websites and services easy and
meaningful. For more information about the Disable cookies Accept cookies and close this message
cookies we use or to find out how you can
disable cookies, click here.
https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views 26/26

You might also like