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

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...

Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality. loginController.js: var loginAdmin=angular.module('Channabasavashwara'); loginAdmin.controller('log ...

jPlayer calculates the "duration" as 1,440 minutes on iOs devices for all mp3 files

My homemade webpage is designed for playing mp3s and viewing pdfs. I'm using jPlayer v 2.9.2 to play the mp3s, which works fine on PC but encounters issues on iPhone. The duration values are incorrect, showing "1439:59" remaining for all files, causin ...

How to extract information from a JavaScript object array in Node.js?

Currently, I am attempting to extract data from a JavaScript Object array by providing field names and then storing the data in an array. However, my current approach seems to be yielding incorrect results. Whenever I try to log the values stored in ' ...

Tips for implementing an onClick event within a NavBar component in a React application

Embarking on my first React project has been an exciting journey for me. I am relatively new to JavaScript, HTML, CSS, and the world of web app programming. My goal is to showcase some information upon clicking a button. In my main default component, App ...

The fixed positioned div with jQuery disappears when scrolling in Firefox but functions properly in Chrome, IE, and Safari

Click here to see a div located at the bottom of the right sidebar that is supposed to behave as follows: As you scroll down the page, the div should change its class and become fixed at the top of the screen until you reach the bottom of the parent el ...

From converting JSON.NET to C# objects

I am attempting to utilize the JSON.NET framework in a Windows Form to extract information from a JSON string. However, I am encountering difficulty in retrieving the Dictionaries from the 'taxonomies->topics' array and the 'clusters' ...

NodeJs - Issue: Headers cannot be changed once they are sent & TypeError: req.next is undefined

My goal is to retrieve data from a MySQL database by calling methods to insert and read information. The reason I am doing this is because node.js operates asynchronously. Here is my code: exports.list = function(req, res){ var moduleRows; req.getCo ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

Learn how to access keys and values within a JSON object by utilizing Json.Net in C# programming

Greetings! I am facing a situation where I have a JSON data structure like the one below: { "Id": " 357342524563456678", "title": "Person", "language": "eng", "questionAnswer": [ { "4534538254745646.1": { ...

Tips for utilizing various broadcast options to trigger Angular controllers according to the user's chosen selection

I'm currently developing an angularjs application that includes multiple date range pickers on a single web page. When a user selects a date range from one of these pickers, I need to send the selected dates to the corresponding angular controller ass ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...

What is the best way to incorporate async and await into my functions within a Node.js environment?

I attempted to implement asynchronous functionality into my code, however, I encountered some difficulties. What steps should I take next? Below are the functions in question: 1. router.post('/urls', (req, response) => { count = 2; webUrl ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

Contrasting the uses of element(...) versus element(...).getWebElement() in Protractor

What is the advantage of using element(...).getWebElement() instead of element(...) when they both perform similarly? Why are there two different APIs for the same purpose? ...

Setting up an object with a set expiration using NodeJS and Mongoose

Is there a way to create a temporary entity (like an ad) that will automatically expire after one month using NodeJS with MongoDB? An ideal comparison would be Instagram or Facebook Stories that only last for 24 hours. ...

What is the correct method for closing a style element in Nextjs JSX?

Having trouble adding some unique styling to a jsx component. The code snippet below is throwing an error when compiled. import Card from "./card"; export default function CardRow(){ return( <> <div> <Card> ...

Efficient ways to temporarily store form data in React JS

When filling out a registration form and clicking on the terms and conditions link, the page redirects to that content. Upon returning to the registration page, all fields are empty and need to be filled in again from scratch. I am looking for a way to ha ...

Turn off automatic calling of Javascript function via the menu

Can anyone help me with calling a JS function from an action link? Here's my declaration: <li><a href="javascript:myFunc()"><span class="glyphicon glyphicon-ok"></span>&nbsp;Test</a></li> The issue is that the ...

Issue with handling .bind in Angular's karma/jasmine tests Angular's karma/j

When writing unit tests for my functions, I encountered an issue with a bound function in the test runner. The problem arose when trying to bind a function to have reference to 'this' inside an inner function. Here is the code snippet in question ...