AJAX with JQuery and MVC

I love JQuery. I used to hate it. But now I love it. I especially love it when working with .NET MVC. I'm building an app at the moment which allows a user to upload a file, and during the process they can choose to have a link to the file sent to them. It's an optional thing, just to save them having to cut and paste a link. It's a nothing feature... a bit of a freebie, and I didn't want to spend a lot of time on it. More importantly, I didn't want to stop the user in their tracks to do this particular task. The email field just sits there in the Nav, and if you want to use it you can and if you don't want to you don't have to. Most importantly, however, if they user did choose to fill in the email box at some point, I didn't want to take them away from what they were doing by doing a full post of the page. Enter AJAX! Ajax is nothing new, and neither is MVC. But in the world of .NET they're both still kinda fresh. So here is how I went about creating a neat little emailer in the middle of a page. First of all, some HTML. The simpler the better!
<form id="EmailForm" action="/test/email" method="post">
    <input id="emailAddress" type="text" value="email address" />
    <input type="submit" value="go" />
Then some JQuery....
$("#EmailForm").submit(function() {                                    //capture the submit event of our form
    $.ajax({                                                           //create an AJAX request
        type: "POST",                                                  //use POST (we could also load this from the form if wanted to)
        url: $("#EmailForm").attr("action"),                           //get the URL from the form
        data: $("#EmailForm").serialize(),                               // this one line turns our whole form into tasty AJAX snacks!
        success: function() {
            alert("win!!!1!1!")                                        //we got a 200 back...it worked!
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("epic fail!")                                         //something went HORRIBLY wrong!
    return false;                            //don't forget to cancel the event so we don't submit the page!
OK, so far so good. All pretty straight forward. That, of course, would work with any server side technology...not just .NET MVC. BUT, the reason I like this so much is because with MVC we don't even have to bother with a responding page. Previously in .NET you'd have to create an ASPX page or web service just to handle this AJAX request (or a library of them perhaps). If you have a route setup already, all we need is a method in our controller class to handle the AJAX request!
public void Email(FormCollection form)
    string emailAddress = form["emailAddress"];
    // validate the email address
    //create the email message
    MailMessage msgMail = new MailMessage("[email protected]", emailAddress);

    // do some email content stuff

    // send the email!
That's all there is to it! Of course, this particular method doesn't return anything to the AJAX callback (except an error if something breaks!)..... so you'd probably want to return something if the address is invalid and show a nice error to the user. But I'm keeping it simple here. The crux of what is cool about this, however, is the separation between HTML and code. Because MVC doesn't have tightly coupled Pages/Classes/Code behind, you can not only reduce the amount of code you write (by doing away with superfluous aspx pages and reusing existing functions), but you increase the number of ways you can use the code you have already written. Doing an AJAX request becomes nothing other than another type of View.... the Controller doesn't have to care where the request is coming from and it means neither do you!

Adding an object with a foreign key in MVC

So you've worked out how to use MVC and the Entity Framework. You can add objects to the database, and you can get them out again, update them and save them back. Awesome! But have you found it cumbersome to create instances of objects just so that you can maintain referential integrity with your foreign keys? I've been reading about on the web about inserting entities to the database, and including references to primary keys in another table. I'm actually surprised the number of ways I've seen this done. This is the most common way I've seen people do it:
Model.Order order = Model.Order.CreateOrder();
order.Customer = (from c in Customer where c.Id == custId select c).First();
When I first saw that, I thought... yeah ok. That could work. I've seen plenty of similar methods as well, revolving around selecting a customer, user, book or whatever by id, return the customer, user or book and then adding it to the object we want to save... and then saving it. The problem here, as far as I can tell is that you end up making an unneccesary select from the database. If we already now the key for the Customer, then we SURELY can just insert that into the table along with the rest of the data?!? Am I right? Yes. I am. Next time you go to create an Order, have a look just under Customer in the intellisense drop down.... you'll see CustomerReference. If your data model is right, this should be an Entity Reference to your customer. This is the key to inserting your Customer ID (pun intended).
Model.Order order = Model.Order.CreateOrder();
Model.CustomerReference.EntityKey = new EntityKey("Model.Customer", "Id", custId);
That's it. That's all you need to do! The only trick to this is sometimes working out what the hell "Model.Customer" should be. The easiest way to find that is to type:
...and let Intellisense come up and remind you what your entity sets are called. By default it can create Customer as CustomerSet or something equally strange (Of course, "db" is whatever your ObjectContext is called). Also make sure you get your casing correct, as customer != Customer :) Alan

Why MVC?

So I've been using .NET MVC and Entity Framework for a while now. I originally started learning about LINQ to SQL about a month before MS announced they were dropping it in favour of EF. Yeah thanks guys. Anyway, my latest project is a collaboration with a guy who has done a bit of Ruby development. Specifically, the website I am helping him rebuild was built using Ruby on Rails. I did spend some time learning Ruby, and getting the app up and running, but given all my stuff is Windows based (hosting, development environment, databases etc), it really was a case of going back to being a beginner. Not such a bad thing, but we wanted to get all this done quickly Given that I am the developer, and I am a fan of .NET, the logical compromise was to go for .NET MVC. We can reuse a lot of the logic from the Ruby MVC app, and simply reimplement it in .NET. In fact, for the most part the views from Ruby translate directly to .NET with little to no work at all.  For an ASP.NET developer (and an ASP dev before that) the whole concept of MVC is a little odd. When you've been working within the page model for so long, it is really quite hard to break out of that mindset. "What do you mean there's no Postback!?!?" Once you get your head around routes, controllers, models and views the rest flows on pretty quickly. As I said, I'd been doing a bit with Entity Framework last year, so at least the Model part of MVC already made sense! I think the best way to explain MVC to a Page model developer (i.e. me) is to think of it in terms of standard Page model app with URL rewrites.  In the past we'd get a URL like /home/news/article/10 and rewrite that in the Request_Start method of Global.asax to go to something like /news/showArticle.aspx?id=10 In MVC, instead of writing a redirect in Request_Start, we add a Route (e.g. {controller}/{action}/{id}) Now, instead of redirecting to a page with some "code behind", we redirect to a View with a controller. The concept is still pretty much the same stuff. Rather than having 1 to 1 pairing of pages and code behind, we have a set of views that all operate off the same controller. The idea here being that all "news" functions will be handled by the News controller, rather than by a dozen different code-behind pages. Conceptually it is a lot neater.  The MVC structure also forces you to be a lot more strict with your HTML design. You will find that you're forced into using partial controls (or user controls as we called them in normal ASP.NET), simply because it is the only way to effeciently get data to the view without duplicating code everywhere. It tends to allow you to focus more on the HTML as one component and the Data as a seperate component, which is how I prefer to think anyway. The two become fairly loosely coupled, unlike ASP.NET where the code-behind and the HTML are joined at the hip. The other benefit is that you only need to worry about requests coming in, and the data that you need to spit out. You can leave the HTML to the designer. MVC isn't a one-size-fits all solution of course. It isn't particularly well suited to applications that rely heavy on user state for example. But it works wonders on Action/Result type applications! The highlight for me, however, is that I don't have to use RoR to acheive RoR-like results!