Insertion Modes
In the last tutorial you caught a glimpse of the AjaxOptions that can be used to augment what your Ajax calls do. In this tutorial we will discuss one of those options, InsertionMode. To keep it simple we will use the same example from the last tutorial of the Ajax ActionLink but see what changing this option does.
InsertionMode.Replace
Using this option will cause the content in the element marked for targetting to be replaced.
The current time plus thirty minutes: well...you have to click the link
InsertionMode.InsertBefore and InsertionMode.InsertAfter
- 2/5/2012 1:57:53 AM -
The Code
The code in the View:
<p><%= Ajax.ActionLink("Add 30 Minutes Before",
"AddTime",
new { minutes = 30 },
new AjaxOptions { UpdateTargetId = "ajaxTargetForInsertion", InsertionMode = InsertionMode.InsertBefore } )%></p>
<p><%= Ajax.ActionLink("Add 30 Minutes After",
"AddTime",
new { minutes = 30 },
new AjaxOptions { UpdateTargetId = "ajaxTargetForInsertion", InsertionMode = InsertionMode.InsertAfter } )%></p>
<p id="ajaxTargetForInsertion">- 2/5/2012 1:57:53 AM -</p>
The controller code is the same as in the last tutorial.
Crowded Output
Nifty, huh? The only problem is with the last example is that the new times just get appended or prepended (a word?) to the content in the target element. Sometimes that is awesome. But if you want something to surround that snippet of text, you will have to do something a little different. Here is one way of doing this differently. This time we surround the new text with a span tag and a space on each end to give us some separation.
- 2/5/2012 1:57:53 AM -
The Code
The code in the View:
<p><%= Ajax.ActionLink("Add 30 Minutes Before",
"AddWrappedTime",
new { minutes = 30 },
new AjaxOptions { UpdateTargetId = "ajaxTargetForWrappedInsertion", InsertionMode = InsertionMode.InsertBefore } )%></p>
<p><%= Ajax.ActionLink("Add 30 Minutes After",
"AddWrappedTime",
new { minutes = 30 },
new AjaxOptions { UpdateTargetId = "ajaxTargetForWrappedInsertion", InsertionMode = InsertionMode.InsertAfter } )%></p>
<p id="ajaxTargetForWrappedInsertion">- 2/5/2012 1:57:53 AM -</p>
The code in the controller:
public ActionResult AddWrappedTime(int? minutes)
{
return Content(" <span>" + DateTime.Now.AddMinutes(minutes.Value).ToString() + "</span> ");
}
The only negative to this is that we are now generating Html in a controller action. It is permissible and sometimes the right thing to do, but has at least two drawbacks as it makes the method harder to test in automation and breaks up the nice separation of concerns between View and Controller. Keep this in mind as you do this.
