views:

1504

answers:

3

I've been developing a simple website using asp.net MVC and I'm starting to add some JQuery\JSON goodness.

My problem is up until now all my 'Views' have been strongly typed and I've been building the view based on data from ViewData.Model.MyViewsData. Now once the view has been rendered and I do a Ajax style request I get new data back as JSON and I need to update my view. Now how can I update my view with the new data when I no longer have access to all the original ViewData?

I'm guessing I need to one of two things, either: always fetch the data back using Jquery\JSON and forget about using ViewData or do some sort of partial rendering of my view?!

Any tutorials or samples would be most appreciated.

Many Thanks

+4  A: 

Hi, I use jQuery and Monorail for an MVC framework - and we use both approaches.

Here's an example for the jquery approach - ignore the fact it's php. The appraoch is the same, namely in the postback function in the jason call, the json return object is accessed direclty to populate front-end controls that are accesed via the css selector.

The alternative is very similar - instead of manually setting control contents, simply apply the html returned in the partial view (ensuring the layout is cancelled as you don't want menus etc just a html fragment).

ip
+3  A: 

ViewData is a server side thing. It is used by the view engine to render your page before it is sent down to the browser. Javascript runs in the browser after the page is delivered. So when you call $.getJson or whatever, you are dealing strictly with the DOM.

Here's a pretty simple example of filling select options via JQuery and MS MVC.

Tim Scott
A: 

If you use the Controller's JSON method to return data for your Ajax request, you can serialize your data to Json and then you have access to it from within your JavaScript. So as an example, If you had a comment form at the bottom of an Article/Blog Post page and you wanted to add the comment via a jQuery $.post call, you could create the comment object in your controller, return it using "return JSON(theNewComment);" and then in your return function in jQuery, you could access the properties of the comment object. You won't get intellisense, but if the object was properly created and returned, the data will be there.

At that point, you need to use jQuery's DOM manipulation capabilities to plug the new values into your comment list (or whatever it is you are trying to update).

Since it's an Ajax call, you shouldn't need all of your ViewData (since the page won't refresh), just the stuff that was created/updated.

Andrew Van Slaars