To create Ajax
links is similar process to creating Ajax forms. Basically, all we
need to do is:
• Use
Ajax.ActionLink() instead of Html.ActionLink()
• Add
AjaxOptions parameter to Ajax.ActionLink() method
To
see how it works. let's build an Ajax link. In the Send Message form,
we want to show a link to display the image of a pet. Please remember
that the main function of Send Message form is to contact pet owner
about a sighting of his pet. It would be very nice to see image of
the pet before sending the message, just to be sure this is the same.
The
code in Figure 1 shows definition of the Ajax.ActionLink(). Please
note that the link is inside a <div> with id “petPhoto”.
When we click, the link will be replaced with the pet’s image. The
code should be placed right after closing bracket of form so that the
link is shown just below Send Message button.
Figure
1. Ajax Link to Load the Pet Photo in the Send Message View
The
Ajax.ActionLink() method
also includes RouteValueDictionary
object, purpose of which to
send name of the pet so that the action method knows the
request is made for which pet. The value in ViewBag.PetName property
is set in Send() action method when the request to send a message is
processed. For example, /Message/Send/Fido which is shown in Figure
2.
Figure
2. Send Action Method in the Message
Controller
The
GetPhoto action
method of PetController class
is shown in Figure 3. These changes produce the result shown in
Figure 4.
Figure
3. GetPhoto Action Method of Pet
Controller and Partial View
Figure
4. Ajax link to load the pet photo
The
GetPhoto partial
view is as follows:
<img
src="@ViewBag.Photo" style="width:150px; height:120px"
/>
No comments:
Post a Comment