Display a division in C# MVC 4 when a boolean value is true by using @Html.DropDownList

I have multiple divs stacked on top of each other, and I want another div to appear when a certain value is selected. I'm familiar with using JavaScript for this task, but how can I achieve it using Razor?

Below is a snippet of my code:

<div id="Attend">
    @Html.DropDownListFor(model => model.AttendWedding, new[]
    {
        new SelectListItem() {Text = "Yes, I'll be there", Value = bool.TrueString },
        new SelectListItem() {Text ="No, I can't come", Value = bool.FalseString }
    }, "Choose an option")
</div>
<div id="Hotel">
    @Html.DropDownListFor(model => model.WillStayAtHotel, new[]
    {
        new SelectListItem() {Text = "Yes, I will stay at the hotel", Value = bool.TrueString},
        new SelectListItem() {Text ="No, I won't stay at the hotel", Value = bool.FalseString }
    }, "Choose an option")
</div>
<div id="Nights">
    @Html.LabelFor(model => model.HowManyNights, "How Many Nights?:", new { @class = "dob" })
    1
    @Html.RadioButtonFor(model => model.HowManyNights, new { style = "width: 1000px; height:50px; overflow:hidden;" })
    2
    @Html.RadioButtonFor(model => model.HowManyNights, new { style = "width: 1000px; height:50px; overflow:hidden;" })
    ...
</div>
<div id="When">
    @Html.TextBoxFor(model => model.StartDate, "{mm/dd/yyyy}",new {@class="datepicker"})
    @Html.TextBoxFor(model => model.EndDate, "{mm/dd/yyyy}", new { @class = "datepicker" })
</div>

So, when someone selects "I will attend," the "Hotel" div should appear, and so forth.

Thank you for any assistance provided.

Answer №1

Utilizing JavaScript is essential for implementing this feature as it operates on the client side. Razor, on the other hand, is interpreted by the server. Alternatively, you could deploy a method where additional fields are displayed after submitting a form to the server and refreshing the page. However, this approach may not be practical in current times. :)

Answer №2

If you're interested, here is my solution and code. I appreciate the help I received earlier:

<script>
    hideAllElements = function () {
        $("#Hotel, #Nights, #When").hide();
    };

    handleNewSelection = function () {

        hideAllElements();

        switch ($(this).val()) {
            case 'True':
                $("#Hotel").show();
                break;
            case 'False':
                $("#Hotel").hide();
                break;
        }
    };
    $(document).ready(function () {

        $("#AttendWedding").change(handleNewSelection);

        // Invoke the event handler once now to ensure everything is functioning correctly
        handleNewSelection.apply($("#AttendWedding"));

    });
</script>
<script>
    hideAllElements1 = function () {
        $("#Nights, #When").hide();
    };

    handleNewSelection1 = function () {

        hideAllElements1();

        switch ($(this).val()) {
            case 'True':
                $("#Nights").show();
                break;
            case 'False':
                $("#Nights").hide();
                break;
        }
    };
    $(document).ready(function () {

        $("#WillStayAtHotel").change(handleNewSelection1);

        // Invoke the event handler once now to ensure everything is as it should be
        handleNewSelection1.apply($("#WillStayAtHotel"));

    });
</script>
<script>
    hideAllElements2 = function () {
        $("#When").hide();
    };

    handleNewSelection2 = function () {

        hideAllElements2();

        switch ($(this).val()) {
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
                $("#When").show();
                break;
            case '':
                $("#When").hide();
                break;
        }
    };
    $(document).ready(function () {

        $("#HowManyNights").change(handleNewSelection2);

        // Run the event handler once now to ensure everything is working properly
        handleNewSelection2.apply($("#HowManyNights"));

    });
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for using str_replace('<') to protect against code injected by users?

Recently, I've been working on a script that involves user input. In this script, I use echo str_replace('<', '&lt;', str_replace('&','&amp;',$_POST['input']));. It seemed like a solid f ...

Utilizing Data Binding with ASP.NET Template Fields

I am looking to bind data to a template field in ASP.NET. In order to achieve this, I can use the following code: Text = '<%#Bind("ColumnName") %>' The Text property represents the control that I want to bind the data to. However, now I a ...

Welcome to the JavaScript NodeJs Open Library!

I am trying to open multiple images simultaneously in the default Windows Photo Viewer that I have stored in my folder using the npm open library: let files = ['Dog.gif', 'Cat.jpeg']; for(let i=0; i<files.length; i++){ open(`${file ...

Updating the redux state in react by passing a variable from a child component to the parent

I'm currently in the process of updating my Redux state within a component by utilizing a variable that has been passed up to the component from a child, specifically through a form submission callback. The form is responsible for submitting a user&ap ...

Retrieve Gridview properties using JavaScript

I need to adjust the font size of my gridview using JavaScript to make it more suitable for printing. What is the best way to change the font size specifically for a gridview using JavaScript? ...

What is the purpose of returning a function in a React Hook?

Currently, I am incorporating Material-UI components into my project and have implemented the AutoComplete component in my application. While exploring an example provided by the Material-UI team, I stumbled upon a fascinating instance of using Ajax data ...

What is the best way to identify a changing ID for each new registered user when using Selenium Webdriver?

As I develop selenium webdriver code in c#, part of my task involves a registration page where, upon clicking the submit button, a message appears at the top saying "Successfully registered with new user having ID as id". Each time I register a new user, ...

What distinguishes loading angular dependencies and what method is optimal for module sharing?

Can you explain the distinction between these two methods of loading modules? angular.module('CoreApp', ['...','...','...','...']); //parent module angular.module('MainApp1', ['CoreApp' ...

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

What is the best way to mix up the images in my memory game?

My JavaScript memory game is functioning properly, but I would like the images to load in a random order. Unfortunately, I'm not sure how to accomplish this. Here is the current setup: var easyImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", " ...

Manipulating toggle buttons using CSS and jQuery

Check out this jsfiddle to see my attempt at creating a toggle switch in the form of a mute button. The toggle button shows the current setting: mute or unmute When hovered over, it displays the alternative setting However, I am encountering an issue wh ...

Including file format extension in the absence of one

I have created a script that loops through every image source on the page, extracting the extension. If the extension is not recognized or does not exist, I automatically add .jpg to the end. Strangely, the if statement always evaluates to true no matter ...

Obtaining the login status of users on my website and displaying the number of users along with their names from the database using PHP

Can anyone assist me with figuring out how to retrieve the login status of users on my website and display the count of users along with their names from the database using PHP or jQuery? Alternatively, I am also interested in simply finding out the num ...

Encountering Challenges when Implementing Next.js with Jest

When attempting to run a test in next.js using jest, an error keeps appearing: The issue may be due to the wrong test environment being used. Refer to https://jestjs.io/docs/configuration#testenvironment-string for more information. Consider utilizing the ...

Assign a value to a cookie using Node.js

I'm currently working on a web project using node.js and express. What is the best way to establish a cookie value? ...

having difficulty placing 3 pop-up windows on a single page

Struggling to implement multiple popups on my page, each with a unique ID assigned. Any assistance would be greatly appreciated. Here is the code snippet: .fa { font-size: 50px; cursor: pointer; user-select: none; } .fa:hover { font-size:20px; t ...

AJAX request function is only successful on the first attempt

Currently, I am implementing AJAX functionality to verify whether a user-input ID exists in the database. If the ID is found, a check mark is displayed; if not, a cross mark is displayed. The issue arises when I input an ID for the first time, which is pr ...

Using third-party libraries like jQuery, CSS, and JavaScript in your React project by directly importing them into the index.html file can be a more efficient approach compared

When working with React, is it advisable to import external JavaScript, jQuery, and CSS files into the index.html file in the public folder? Are there any potential performance implications associated with this practice? I have utilized some jQuery functi ...

Choosing a component without an identifier

Trying to select an element from a webpage can be a bit tricky. After inserting a control into the page and needing to set some values for an element inside the control at pageload from C# code, you may encounter issues with id prefixes being appended due ...

What is the best way to direct users to the individual product page once they make a selection

On my main products page, I am fetching all the products from a local JSON file. interface productItem { id: number; name: string; image: string; price?: string; prices: { half: string; full: string; }; ...