Scott Hanselman

ASP.NET MVC Preview 4 - Using Ajax and Ajax.Form

July 17, 2008 Comment on this post [51] Posted in ASP.NET | ASP.NET MVC
Sponsored By

ASP.NET MVC Preview 4 is up on CodePlex. The Gu has all the exquisite Gu-Like Detail on his blog. Phil Haack has some notes on this release on his blog.

If you take a look at the generated "changes" document, it shows a bunch of new stuff like AjaxHelpers and AjaxExtensions that set the stage for some interesting things the community could do with ASP.NET MVC and Ajax. I'd like to see some JQuery love in there, maybe with some MVCContrib as they've been quiet lately.

Using the new Preview 4 bits, here's what I was able to get running in just a few minutes.

Given a ViewPage that has a TextBox and a Button on it, when I click the button (and submit the form) I'll call back to the server and get some text that should then go in the div next to the button.

mvcpreview4ajax

The View looks like:

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<p>
<%using (Ajax.Form("ExamineTextBox", new AjaxOptions { UpdateTargetId = "result" }))
{ %>
<%= Html.TextBox("textBox1")%>
<input type="submit" value="Button"/>
<span id="result"/>
<% } %>
</p>
</asp:Content>

Notice the Ajax.Form helper and the UpdateTargetID that refers to the span. There's more AjaxOptions in there to explore as well, that we'll see in a second. The controller action looks like this:

public class HomeController : Controller
{
public string ExamineTextBox(string textBox1)
{
if (textBox1 != "Initial Data")
{
return "This text is MVC different from before!";
}
return String.Empty;
}
}

Notice that the return method of the ExamineTextBox isn't an ActionResult, it's a string. In fact, the string result is being wrapped for you into a ContentResult. You could certainly make a ContentResult yourself, but this makes for a nicer looking method signature.

The result of that method is returned via the AJAX call, then put into that span via magic and pixie dust. Actually, the request looks like this:

POST /Home/ExamineTextBox HTTP/1.1
Referer: http://localhost.:45210/Home
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Accept-Encoding: gzip, deflate
Host: localhost.:45210
Content-Length: 28
Connection: Keep-Alive
Pragma: no-cache

textBox1=dude&__MVCAJAX=true

and the Response like this:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 39
Connection: Close

This text is MVC different from before!

And that UpdateTargetID (the span) mentioned in the Ajax Form helper above? That's swapped in via the magic in MicrosoftMvcAjax.debug.js. There are options for before, after and replace.

// Insert the results into the target element
if (targetElement) {
switch (insertionMode) {
case Sys.Mvc.InsertionMode.Replace:
targetElement.innerHTML = executor.get_responseData();
break;
case Sys.Mvc.InsertionMode.InsertBefore:
targetElement.innerHTML = executor.get_responseData() + targetElement.innerHTML;
break;
case Sys.Mvc.InsertionMode.InsertAfter:
targetElement.innerHTML = targetElement.innerHTML + executor.get_responseData();
break;
}
}

Note that I had to manually (for now) add the JavaScript libraries, so I put them in my Site.Master View.

<script src="/Content/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="/Content/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>

Also, notice that the MicrosoftMvcAjax.js is new and it's in your /Content folder if you make a new MVC Application. Congrats to Phil and Eilon and the team for this release!

Related Links

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
July 17, 2008 4:55
I just downloaded Preview 3 last night... lol
July 17, 2008 5:31
i HOPE it's not the javascript library from asp.net ajax! if it is anywhere close, why bother? who wants the bloat? jQuery or YUI support would be great perhaps much in the same way Ext JS creates adapters for different libraries but then it's even more bloat. i wonder how many other developers outside of MS will use the AJAX when this is so easy to do with the MVC framework and jQuery. i guess this is for webform developers who needs this stuff pre-canned for them. give me bare metal MVC!

anyway, i didn't mean to be negative. all this stuff is great. i hope there will be an article on using IronRuby with ASP.NET MVC Preview 4. there was supposed to be some support from it if I remember correctly.
July 17, 2008 6:51
@Mike We're definitely looking into the idea of having more JQuery support one way or another. Several members of the ASP.NET team are fans of JQuery. I'll post some samples of using MVC Ajax w/ JQuery soon.
July 17, 2008 7:37
Well, i have to say that I like jquery also. But don't ride off the implemantation of ms ajax only for winforms people who demand canned easy to use things. Fact of the matter is somtime a project roles around with the requirment that no opensource libraries be used. and that whatever it is being used is somthing to be garanteed supported by a Company like Microsoft.
July 17, 2008 8:01
I've started a series of posts detailing the creation of a Grid html helper using AJAX and JQuery using the preview 3 bits here. I'd love some feedback/help.
-Seth
July 17, 2008 8:12
Hi Scott/Phil

Thanks for the post.Different choices are good things and I am happy that MVC is pluggable to any client side javascript frameworks. If anyone like jQuery or other frameowork, they can use that one and anyone like MS Ajax they can use it. Don't argue for a single framework. The MVC team should learn lesson from the problems of ASP.net Ajax while developing Ajax helpers for MVC. The fact is that JQuery is very popular among the web develoeprs regardsless of specific community.Please provide samples in both JQuery and MS Ajax.

Thanks,
Shiju Varghese
July 17, 2008 12:06
Although it works nice, I'd prefer an unobtrousive JS solution. I mean, I hate the standard ASP.NET AJAX framework for the bloat, the use of updatepanel and all that non-standard stuff, but at least it works in an unobtrousive way, so if the have JS disabled the page works in the normal way.

I'll stick to my custom self-written ajax library for now, hoping to see something in the future. The MVC framework is awesome, been waitin for it for ages, and all you guys are doing wonders, keep it up!
July 17, 2008 13:50
I noticed that when I refresh my page it doesn't loose value in textBox! What is it? View State come back? Why I ever need this? How can I disable?!
July 17, 2008 16:59
I created some jQuery love for preview 3, and will also do this for preview 4 ofcourse... though it's too bad to see that p4 does not allow you to override the default ajaxhelper :( ... all methods are non-virtual.
July 17, 2008 17:06
Hmm, openid doesn't give much about my identity :)
Anyway, forgot to include a link to my p3 version of jQuery love
July 17, 2008 17:28
+1 for jQuery

I'm missing HtmlHelpers such as SubmitButton, Image - were they removed?
July 17, 2008 17:42
What's even better, is that it's optional and I don't have to use it. Unobtrusive is the way to go.
July 17, 2008 18:00
Support jQuery.

No Asp.net ajax!!!!!!!!!!!
July 17, 2008 18:27
Just makes me cry that so much effort is being spent on these helpers (that anyone working with a good AJAX library doesn't need) instead of working on things like subcontrollers and components... :(
July 17, 2008 19:13
NIrvana, I've been using the <a href="http://developer.yahoo.com/yui/>Yahoo! User Interface Library</a> with ASP.NET MVC without any problems, and I suspect you could easily do the same with JQuery. What I like best about ASP.NET MVC is that it provides me with a lot more control over my output than I ever felt like I had with ASP.NET WebForms.
July 17, 2008 20:08
This looks like you are replicating the UpdatePanel behavior at some degrees
July 17, 2008 20:57
@Simone Nah, definitely not replicating UpdatePanel. UpdatePanel is a very different beast. It's focused on setting a region as "asynch updateable" and forget about it. There's a lot of magic involved to get it to work. It has to understand __VIEWSTATE, etc... This is very different from UpdatePanel. It's not fire and forget. You need to be explicit. You have full control. It's very lightweight.

@Jamie We wanted to provide a small set of simple Ajax helper methods for those who aren't as familiar with Javascript libraries. These can enable simple scenarios, and we don't plan on having a huge number of them. For that, I think they still provide value and for those who are competent with good JS libraries, you can totally ignore them. We'll also be digging into various ways of swapping in JQuery. Watch my blog for some posts on that.
July 17, 2008 22:07
too difficult
July 17, 2008 22:45
has page invoke page methods ?
July 17, 2008 23:50
Could you do readme in PDF in the future? Thanks!
July 17, 2008 23:59
Mike - There should be DOC and PDF versions of all the files on CodePlex.
July 18, 2008 0:12
there's a bug in the ButtonsAndLinkExtensions class.

the button builder always builds a closed tag button, which is invalid and causes serious rendering bugs in the HTML. the button tag has to be open:

<button arg="val">Text</button>
July 18, 2008 0:14
Good find, Carl! I'll pass it on.
July 18, 2008 0:28
looking forward to this release... I'm a fan of both JQuery and ExtJS.
July 18, 2008 1:25
I just ran this sample, but how can you prevent your form from losing the text in the textbox after submit? It doesn't seem like the desired behavior in many ajax application.
July 18, 2008 1:40
You'd have to put the text right back into the Textbox, I'm afraid!
July 18, 2008 19:08
Is it too late to complain about the misuse of the 'using' keyword? Are we really freeing an unmanaged resource by calling Dispose on a Form object (or whatever object is returned by the call to Ajax.Form)?

How about something less abusive, like:


<%= Ajax.Form(...) %>

<%= Ajax.EndForm() %>


July 18, 2008 19:29
ps. This is really a horrible example. :)

How about changing it to something where you're at least doing some sort of server side validation on the textbox input instead of something that could have been done without the postback to the server.

I'm just saying it's a really confusing example... and it's hard to see what you're exactly getting with Ajax.Form.


1. <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
2. <p>
3. <% using (Ajax.Form("UsernameExists", new AjaxOptions { UpdateTargetId = "result" }))
4. { %>
5. <%= Html.TextBox("username")%>
6. <input type="submit" value="Button"/>
7. <span id="result"/>
8. <% } %>
9. </p>
10. </asp:Content>

public class HomeController : Controller
{
public string UsernameExists(string username)
{
string[] existingUsers = { "ScottGu", "ScottHa", "GuyIncognito", "Boris" };

if (existingUsers.Contains(username))
{
return "The username is already in use";
}
else
{
return "The username is available";
}
}
}



@me.yahoo.blahblahblahb


I haven't run this example yet, but if it's truly an "ajax" example, the entire page should NOT post back to the server and reload entirely (which would cause you to lose whatever value was in the the textbox). The postback should happen behind the scenes without the page reloading. I'll have to try out the new MVC 4 bits and see what you mean, cause I'm confused...
July 18, 2008 20:39
Guy - Valid point. I did it in like 2 minutes. Your example is a good one!
July 20, 2008 8:42
zbleo vegoti qecvifsl wrzkpbgjl wvaj bpry yxiequokd
July 21, 2008 1:03
trying out openid
July 21, 2008 21:41
I don't know why everyone is so into jQuery. Every prototype based library offers kind'a the same access elements. More to the point I like the idea of MooTools more than I do jQuery.

And also I'll much more like to use ASP MVC Ajax rather than jQuery. It is a matter of personal preferences after all. I for one have never used ASP.NET before mostly because I didn't find it appealing enough. Ever since MVC was introduced things changed and I hope it will be ready for release soon =p~.

Congrats to the MVC Team you are building a great piece of software.

July 22, 2008 0:25
What adjustments do you have to make at the IIS in order to publish the .net website using MVC framework?
July 22, 2008 0:34
Tania - For IIS7, nothing, it just works. For IIS6, you need to associate the MVC extension with the ASPNET_ISAPI dll.
July 22, 2008 13:20
@GuyIncognito: I like the "using" syntax. It think it's far more readable than a lot of Begin() / End() blocks (it won't compile in case of errors, whereas it would just spit out invalid HTML otherwise).

I'd vote for jQuery support too. :)
Lck
July 22, 2008 16:59
So, .net MVC not even a beta yet. Do you have a timeline for the releases? I would like to know it because we are planning to use it for a very important project of ours. Thanks!
July 22, 2008 20:20
Tania - I think MVC will be released in a month than ends in "-ber."
July 23, 2008 20:28
Hi Scott. Thank you for your responses.

I worked at a Flex shop previously and am familiar with the Cairngorm MVC. You can consider me 'relatively' new in the .NET arena. I have a few more questions -

1) Where are you keeping the state - server? Saw the runat="server" controls on your examples. What happens when one page depends on the input values from other pages? I am used to keeping it in the Model as Value Objects.

2) How does the 'session' come into play in this?
July 25, 2008 9:50
Hi Scott,

You guys are doing great work with MVC and the Ajax helpers. One question though: why are the helpers sealed? That could be a great extensibility point for other JS frameworks.
July 25, 2008 19:14
Hi Scott!

Here is the jQuery love you asked for:
http://blog.goeran.no/PermaLink,guid,e55bfb55-ac10-48db-98a4-d28343e0f98a.aspx
July 25, 2008 19:25
Hi Scott!

Here is the jQuery love you asked for:
http://blog.goeran.no/PermaLink,guid,e55bfb55-ac10-48db-98a4-d28343e0f98a.aspx
July 29, 2008 9:44
Thanks for the simple post; sometimes the 2 minute ones are the best ;).
August 11, 2008 13:44
How about a new insertionmode for the Ajax helper to write to the outerHTML instead of the innerHtml therefore replacing the target completely.

Here's the scenario. I have a table and at the end of each row is a delete button when I press the delete button I want to delete the item and remove the row from the table using the Ajax.ActionLink I can set the target to the id of the row and remove the innerHTML but this doesn't completely remove the row causing the html rendering to show a couple of pixel gap where the row used to be. This makes the table look messy. I could surround the tr tags with span or div however this isn't exactly valid XHTML









Ian
August 12, 2008 2:58
I've tried with FF and all works fine.
I've tried with IE 7 and the HTML was messy after the async callback because of the way the result was rendered (the footer goes away).
I've changed the markup to fix it up: <span id="result"></span>
August 19, 2008 22:01
Scott,

So September it is! Ah, just kidding, but not really.
August 19, 2008 23:32
From personal experience, the only issue I'm having with this current setup is that the receiving action can no longer view the Request object for the value of the submitting button.

for example:

<%using (Ajax.Form("Update", new AjaxOptions { UpdateTargetId = "result" }))
{ %>
<input type="hidden" id="id" name="id" value="foo" />
<input type="submit" id="submit" name="submit" value="Add"/>
<span id="result" />
<% } %>

(note: the above code was never run, so there may be an error or two)
in the action, I cannot view the value of my submit button. I tested with the hidden input, and that worked great, but on a form that has several buttons, you need to be able to pull out the value, or have a different way of distinguishing which of the buttons was pressed.
August 25, 2008 21:31
You'd have to put the text right back into the Textbox, I'm afraid!


Hey Scott, any way to avoid this and have this app behave like an Ajax app should? I need the form data to remain in the form after the asynch form submission.
August 26, 2008 7:17
There´s a nice sample about ASP.NET MVC and Ajax Forms on http://sharpmasters.blogspot.com/.
September 09, 2008 6:24
Okay, question. How on earth do I get the javascript includes to work in my page?

Using <script type="text/javascriptscript" src="../../Content/MicrosoftAjax.debug.js"></script> certainly doesn't work! Unlike <link/> tag for CSS, where it automatically resolves it relative to current page, it doesn't do this for scripts. And I can't seem to find any other way to get it to register using code behind.

Someone save me from my stupidity trying to get this to work! :P
September 10, 2008 8:18
Wow. MVC looks a lot like ruby on rails.

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.