views:

66

answers:

4

I want to create a shared control where i want to generate markup according to the role of logged in user. TO achieve this I need to call a method in Model class. Is this a right way to do this in ASP.NET MVC as I heard that we should strictly separate out Model and Views. Please help.

A: 

The Models and Views should only be separated to the extend that the direction of communication should go in only one direction. Typically, a View will know about the underlying Model, but not the other way around.

This is why ASP.NET MVC has the concept of strongly typed View where Views can be strongly bound to a particular type of Model.

As such, I don't see any problem with coupling your View to a member of the Model class.

Mark Seemann
A: 

Whilst it's fine to read from your model via a helper extension. is this required to create large amounts of markup? if so i would question if this is the optimal approach?

You could consider using the "asp:loginview" and render partial views from here? ASP.NET Controls that dont rely on viewstate work fine in MVC.

Example:

<asp:LoginView id="LoginView1" runat="server">
                <RoleGroups>
                    <asp:RoleGroup Roles="Admin">
                        <ContentTemplate>
                            <%= Html.RenderPartial("MyPartial"); %>
                        </ContentTemplate>
                    </asp:RoleGroup>
                </RoleGroups>
            </asp:LoginView>
Mark
+1  A: 

In my opinion, the View should not know what a Role should see. It is a Controller function. In the same way, Model should not concern itself with how the View uses its information.

So, here is how I design it.

The View asks for information. The controller should know who the user is, and what they should see. The controller asks the Model to give the right stuff to the View.

It is nice if you could design the system so that it can manifest itself with no Model or View.

srini.venigalla
A: 

In MVC Futures you also have the Html helper RenderAction, which allows your view to call and action and it then renders the result of that action within its own mark up.

This is helpful for doing things like menu's and so on, but this is not strictly MVC, but it is very practical.

But the best method to use is going to depend on the html you need to output, where you need to output it and why. If you could tell us a bit more about the Html you need to render and its purpose that would be good and we can give you some better help.

But one thing is for sure, Models should not be outputing Html to render.

theouteredge