Mostly, a view is dynamic, data-driven.
The driving data, if finely categorized, falls into two parts: business data and render-assistant data. I'd like to separate render-assistant data out because practically it comes from a different source, rather than business repository, but the security module, where user roles and privileges are defined.
So I can map a security role to a list of render-assistant parameters, and customize a generally defined View or a Partial View similarly, with them.
I can design a view or partial view to let it expose rendering parameters, then let the controller to DI (Dependency Injection) for that parameters.
Now, my data-driven view becomes a role-driven view.
Following is a demonstration, where RenderParameters is a list of key-value pairs and it is passed into a view as ViewData or ViewModel. Then the Inline code of a view implements logics based on the RenderParameters.
ViewParameters
ViewParameters is a collection of key-value pairs (bag) for holding parameter values. For simplicity, the following code defined the type under ViewModel namespace.
namespace MvcApplication1.ViewModel
{
public class ViewParameters : Dictionary<string, string>
{
}
}
Then, in a view or partial view we can define the rendering logic based on ViewParameters. In following code snippet, ViewParameters are passed in through ViewModel - strong-typed partial view.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ViewParameters>" %>
<%@ Import Namespace="MvcApplication1.ViewModel" %>
The second line in above code snippet is to ensure a reference to the parameter class. Once parameters are passed to the view, then the view code can implement logic by using them. e.g.
<%if (Model["xx"] != null && Model["xx"] == "yes") {%>
shown in one case.
<%} else {%>
shown in other case.
<%}%>
In our example, we defined a partial view that has to be rendered from a view. Note, a partial view shares ViewData and ViewModel from the view where it is rendered. Following tag renders the partial view VenderRegistrationSum, where I defined the custimization logic.
<% Html.RenderPartial("VenderRegistrationSum"); %>
Finally, In controller we need to prepare the view parameters. E.g.
// demonstrate partial view parameterization
ViewModel.ViewParameters p = new MvcApplication1.ViewModel.ViewParameters();
p.Add("xx", "yes");
return View(p)
No comments:
Post a Comment