What
this means is that instead of making a synchronous request to server for
sending the messages? The form will now send an asynchronous request using
Ajax. The modifications are shown in Figure 1. Following modifications need to
be done:
• Enclose the <form>
in <div>
element and set id "messageForm" of
the <div>. What we want to replace the <form>
with the data returned by the request
execution when the request gets completed successfully. The <div> will
be used in UpdateTargetId property of the AjaxOptions
parameter.
<div
id="messageForm">
<form>
//Some
HTML content
</form>
</div>
• After the messageForm
<div> please add another <div> with
id "loading". This HTML element will be shown when the request will be
processed. Add the text “Sending Message ……” to the loading div and set its
display style to “none” to hide it by default.
<div
id="loading" style="display: none">
Sending Message ……
</div>
• Now
change the definition of form from Html.BeginForm() to
Ajax.BeginForm(). It will change the behavior of form and it will process
the request asynchronously.
• Add an AjaxOptions
object to Ajax.BeginForm() call
with following settings for processing the request:
• Add one confirmation message.
• Set HTTP method to Post.
• Set InsertionMode property to Replace.
• Set LoadingElementId property to loading.
• Set UpdateTargetId property to messageForm. The objective will replace the entire
form with received
response from server.
Figure 1. Form to be an Ajax form
To
complete the functionality, we need to make one more changes to controller:
render the ThankYou view like a partial view instead of full view. The ThankYou() action
method is used to return an specific markup view to thank the user to send a
message. We want to change its behavior to render only a partial view which we
only need to send HTML which will replace the form when the message will be successfully.
The modification is shown in Figure 2 below:
Figure 2. Modified ThankYou Action Method
Please that the action method was changed to return PartialViewResult of the object.
PartialViewResult inherits
from ActionResult that’s why it can be used as a return type of an action
method.
The only restriction of using PartialViewResult is
that the returned object must be an actual partial view and not any action
result object that’s the return statement uses PartialView().
When we send a message then the form first displays the
confirmation dialog box as shown in
Figure 3. When the user clicks the “OK” button then the loading message will be
displayed at the bottom of the page as shown in Figure 4. Once the request is
Processed then the message will be displayed in the partial view ThankYou which is shown in Figure 5.
Figure 3. Confirmation
dialog when sending a message in the Ajax form
Figure 4. Loading element shown during
request processing
Figure 5. Partial view returned
from request and inserted in HTML element
No comments:
Post a Comment