I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.
My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.
Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.
I've done something similar for an app I'm working on. I have partial views returning rendered content can be called using their REST path or using:
Then in my actual display HTML I have a DIV which is filled from jQuery:
The jQuery looks like this:
This scans for all DIV that match the "onload" class and reads the REST path from their content. It then does a jQuery.load on that REST path and populates the DIV with the result.
Sorry gotta go catch my ride home. Let me know if you want me to elaborate more.
You have several options.
Create a MVC View User Control and action handler in your controller for the view. To render the view use
In this case your action handler will need to pass the model data to the view
Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent:
If your user control has it's own data type you can also construct it within the page
In MyControl.ascx.cs:
And in your page you can initialize your control's data model:
After much digging in google i have found the answer. You can not get easy access to the html outputted by the view.
http://ayende.com/Blog/archive/2008/11/11/another-asp.net-mvc-bug-rendering-views-to-different-output-source.aspx
You would create your action like this:
And the action would return the rendered partial view to your jquery response.
Your jquery could look something like this:
I found this one line code to work perfectly. orderModel being my model object. In my case I had a helper method in which I had to merge a partial view's html.
I put together a rough framework which allows you to render views to a string from a controller method in MVC Beta. This should help solve this limitation for now.
Additionally, I also put together a Rails-like RJS javascript generating framework for MVC Beta.
Check it out at http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc and let me know what you think.