views:

918

answers:

2

I'm currently porting an ASP.NET WebForms application to ASP.NET MVC.

In one of the pages there is an ASP.NET Label control which is displayed conditionally based on a variable in the codebehind. So, something to the effect of

<asp:Label runat="server" Visible="<%# ShowLabel%>">
...
</asp:Label>

Where ShowLabel is a Boolean value in the codebehind. The contents of the label are generated at runtime and will be different pretty much every time.

There's better ways to do this even in ASP.NET, but what would be the best way to do this in ASP.NET MVC? How are you even supposed to render dynamic text in ASP.NET MVC in a way similar to how the ASP.NET Label object worked?

+2  A: 

I believe in the Thunderdome principle of having one ViewModel class for each View (unless it is a very simple view).

So I would have a ViewModel class like the following:

public class IndexViewModel   
{
    public bool labelIsVisible { get; set; }
    public String labelText { get; set; }

    public IndexViewModel(bool labelIsVisible, String labelText)
    {
        this.labelIsVisible = labelIsVisible;
        this.labelText = labelText;
    }
}

In your controller, do something like,

public ActionResult Index()
{
    // Set label to be visible in the ViewModel instance
    IndexViewModel viewData = new IndexViewData(true, "Simucal rocks!");
    return View(viewData);
}

Where Index is a strongly typed view of type IndexViewModel.

Then, in your view simply do something like:

<% if (Model.labelIsVisible) { %>
 <%= Model.labelText %>
<% } %>
Simucal
A: 

The main idea in MVC is NOT to pass the strings you want to display; you should pass the relevant objects to your View, and the View, in turn, would decide wether to display that label or not (and this is using a simple if, like in Simucal's sample).

So, instead of doing

if (Model.labelIsVisible) {

One would do

if (Model.Comments == 0) {

For example, if the label would be to show a prompt for a user to comment on an article.

synhershko