Kailas
Kailas

Reputation: 449

How to dynamically change the visibility of label in mvc3?

I have the following code

<div> @Html.LabelFor(m=>m.WrongLogin) </div>   

I want to display the label dynamically based on a condition from the server side code in the controller. If the controller returns false value then I need to make the label visible.

Upvotes: 2

Views: 4836

Answers (3)

Rajeshkumar Kandhasamy
Rajeshkumar Kandhasamy

Reputation: 6461

There is another one way in Jquery,

By default make the Div Invisible and set the div Id. Like Below,

In .cshtml

<div style="display:none" id="DivWrongLogin">
        @Html.LabelFor(m=>m.WrongLogin) 
</div> 

In Script

$(document).ready(function () {
     if('@Model.LoginFailed' == false)
     {
         $('#DivWrongLogin').show();
     }
});

Upvotes: 2

Ashwini Verma
Ashwini Verma

Reputation: 7525

As Jon Skeet answer is correct, you can use ViewBag if you don't want Model.

Controller

public ActionResult Index()
{
    ViewBag.IsValid = false; //or true based on your condition

    return View();
}

View Page

@if (ViewBag.IsValid)
{
    <div>@Html.LabelFor(m=>m.WrongLogin)</div>    
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503439

Just use an if statement:

@if (Model.LoginFailed) // Or whatever...
{
    @Html.LabelFor(m => m.WrongLogin);
}

Upvotes: 6

Related Questions