ASP.Net MVC - Server-side Include when bound to viewmodel
I am just learning ASP.Net's MVC framework and so my question is likely basic. But I need assistance with re-usability of web pages when tightly bound to View Models.
Consider an application like the following:
Screen 1: Search for the closest library by typing in your street address. The library displays after the search, the page having been tightly bound to the Library View Model.
Screen 2: Search for your registration information by name and date of birth and include in the results the closest library, in exactly the same layout as screen 1. This screen shows more information than screen 1 because it is bound to the View Model of R开发者_StackOverflow社区egistration, which contains a Library View Model as a property.
I want to reuse Screen 1, essentially doing an "include", so that all my HTML for Screen 1 does not have to be rewritten in Screen 2.
But how do I do that when both are tightly bound to different View Models?
I'm probably not even searching with the right vocabulary. Any guidance to the appropriate functionality would be appreciated.
The HTML which will be used in both Screen 1 and Screen 2, should be placed inside a Partial View. Partial Views are like User Controls which can be used in multiple screens.
Bind that Partial View to the Library View Model.
In your screen 2, you can render the Partial View using the following code:
<%: Html.RenderPartial('LibraryPartialView', Model.LibraryViewModel) %>
Here we are rendering the library partial view in screen 2 and passing it the Library View Model object (which is initially contained in the Registration View Model; Here Model
refers to the Registration View Model).
In Screen 1 you would have to Render Library Partial View using the same code.
Additionally, you can also load it using ajax and jQuery. Something like
<div id="libs">loading...</div>
$("#libs").load("/libraries/address/12-w-6-ave");
Or if the libraries are not part of the model ( in case you prefer it not to be) you can just load the action as if it were a separate request
@HTML.RenderAction("action", "controller", new {id=Model.Address})
Both those methods allow you to separate the registration info from the library info, if you need/prefer that.
精彩评论