ExtJS and .NET MVC

I've been using JQuery with .NET MVC for a while now, and it works wonderfully. I've made a couple of post previously on the subject. In my most recent project I've been using ExtJS with .NET MVC and it works wonderfully well (for the most part!). Since the latest version of ExtJS (v3) came out, it has gotten a whole lot easier with full REST support for data stores. When I first sat down to write my data components for this particular project, I made my subclass of the Store class (or JSONStore depending on what I was doing), and implemented my own REST-style interface. This basically involved providing a URL and then appending _get, _set, _delete etc to get the appropriate URL. It was messy and ugly and didn't work like REST should. Fortunately, around this time version 3 of ExtJS came out and solved all my issues in one go. Now by including the property "restful:true" into your Store, the store will automatically wire up the get, set, update and delete methods for you.
var store = new Ext.data.Store({
restful: true,
...
In my case, I am using a datagrid with a row editor. This means that when I click add, delete, update or load, the data store will take care of everything. All I need to do is provide a URL. Now, most ASP.NET developers will have never come across this, but it's definitely something you should be aware of. All 4 actions use the same URL (and hence the same method name in the controller) but with varying HttpVerbs.
[AcceptVerbs(HttpVerbs.Delete)]

        [AcceptVerbs(HttpVerbs.Post)]

        [AcceptVerbs(HttpVerbs.Put)]

        [AcceptVerbs(HttpVerbs.Get)]
What this means is that in your controller you can have ONE method name (but 4 separate methods) to handle all requests for this data type. Not only is it a lot neater, it's a lot easier to understand.

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" />
</form>
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!
[AcceptVerbs(HttpVerbs.Post)]
public void Email(FormCollection form)
{
    string emailAddress = form["emailAddress"];
    // validate the email address
    .....
    //create the email message
    MailMessage msgMail = new MailMessage("info@angrymonkeys.com.au", emailAddress);

    // do some email content stuff
    .......

    // send the email!
    smtp.Send(msgMail);
}
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();
db.SaveChanges();
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);
db.SaveChanges();
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:
db.
...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