Create a dropdown list with the same name based on certain conditions

In my code, I have a specific condition coming in from the Model to determine whether I am in create mode or edit mode. If I find myself in Edit mode, I need to ensure that the dropdownlist shows the last saved value. However, if I am in create mode, the dropdownlist should default to a predefined value.

*.ASCX

<% if(Model.isCreate == true)
   {
        Html.DropDownList("myOptionListName", 
                           new SelectList(ViewBag.MyOptions, "Id", "Name"),
                           Resources.Global.DefaultMenuItem, 
                           new { style = "width:200px" });
   }
   else
   {
        Html.DropDownList("myOptionListName", 
                           new SelectList(ViewBag.MyOptions, "Id", "Name", 
                           ViewBag.LastSavedOption), 
                           new { style = "width:200px" });
   }%>

It is crucial for me to use the name "myOptionListName" due to other JavaScript functions referencing it. Unfortunately, at the moment, the current code does not render the dropdown at all.

How can I modify the code to display the menu based on the conditional check while keeping the same name for consistency?

Answer №1

To create a customized select list for your control, consider setting it up based on the form's mode and then assigning the appropriate options to it.

<% var customList = new SelectList(ViewBag.MyOptions, "Id", "Name");

   if(!Model.isCreate)
   {
        customList = new SelectList(ViewBag.MyOptions, "Id", "Name", 
                           ViewBag.LastSavedOption);
   }

   Html.DropDownList("customSelectListName", customList , 
                           new { style = "width:200px" });
   %>

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

How to handle single quotes in .NET by adding slashes to escape them

I'm currently working on some code that concatenates SQL queries in the following way: string sql = "SELECT* FROM table WHERE column = '" + value + "'"; However, I've discovered that if the value variable contains a ' character, ...

One page supports the dialog method, while another page does not offer this feature

I am facing an issue with 2 .NET web pages that have the same popup box. The JavaScript code is identical in both pages, as I copied it from the page that is working fine to the other page. However, on the page where I pasted the code, the popup box is not ...

Generating numerous threads rapidly and running them almost concurrently

In my C#.NET application, I am facing the challenge of notifying a large number of connected devices, ranging from 4000 to 40,000, to perform a task simultaneously or as close to it as possible. Although the application is functional, the performance leav ...

Adjusting the styling of slick.js carousel when the slide changes

Is it feasible to change the CSS for a div on a slick.js slider change? Essentially, I want to cycle through an array of colors and set the background color of .content to that color when the slider autoplays or when a button is clicked. Am I being too amb ...

Experiencing difficulties with executing numerous NodeJs queries

Could someone assist with rendering multiple queries in a Nodejs view? The console shows Promise {pending} and I can't figure out what's causing the issue. I'd appreciate any help or guidance on how to fix this problem. router.get('/ ...

Collaborating with interactive icon in input group

I'm having trouble getting the textbox and icon to be in the same line, like a bootstrap input group. The icon is also clickable. <div class="input-group"> <asp:textbox id="txtParentCategoryCode" runat="server" cssclass="input-text normal" m ...

A step-by-step guide on how to smoothly hide an element using ng-hide in AngularJS

Currently, I am able to toggle an element's visibility based on a boolean condition in my controller. However, I am looking for a way to smoothly fade out the element if the condition is true instead of instantly hiding it. Any suggestions on how to a ...

Guide on changing the font size of a selected tab in material-ui

My requirement specifies that the active tab should be styled with a specific color and font size only. Here is my code snippet: <Tabs value={value} onChange={handleChange} ...

What is the best way to retrieve the complete file path of a FilePathResult file in asp.net mvc 3?

Is there a way to retrieve the last modification date of a file returned by an action method? I believe I will need the full file path in order to accomplish this. The FilePathResult object has a property called FileName. Does the FileName property return ...

Delivering a JSON response containing an item within an array

I am struggling to find the correct way to access the error message related to the 'firstname' field in the JSON-encoded object. The error message states that the length of the value for 'firstname' must be at least 3 characters long. ...

I can't seem to locate my client-side socket.io

I have successfully built an isomorphic React application using Express and React-Engine. Currently, I am in the process of integrating socket.io. In the Express setup, my code looks like this: var express = require('express'); var app = express ...

Verify whether any data exists when transferring information

My goal is to create a migration that establishes an admin user with a specific role. My initial plan was to incorporate an assert statement to verify the existence of the role and ensure there are no pre-existing users with that same role. However, I have ...

The value in a JSON can alternate between being a string or an object at times

I am facing a challenge with JSON data that can have two different formats. In one format, the location value is a string, while in the other format it is an object. Here is an example of the first format: { "result": [ { "upon_approval": "Pro ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

Transforming HTML Table into Image Format

Is it possible to transform an HTML table into an Image file? I have an HTML table with elements such as Labels, GridView, and CheckBoxes. How could we go about converting this table into an Image file in order to generate a PDF document? ...

Tips for referencing a string in JavaScript

I am trying to use the showmodal method, but I keep getting an error when passing a string. It works fine with integers, but how can I pass a string in JavaScript? <script> var table = ' <table id="example" class="table table-striped " w ...

Generate a unique identifier and verify its presence within an array of objects

Is there a way to generate a unique identifier and add it to an object in an array, only if the id does not already exist in any other objects within the array? Within the React code snippet provided below, the "saveColor" function was intended to accompl ...

Conceal on External Click with AngularJS

My code looks something like this... I am using the 'left-menu-active' class to toggle the menu in css... I have two issues and I am looking to resolve them using angular js... I want to dynamically add a class to the parent element using angu ...

`The Issue with Ineffective Slider Removal`

Below is the complete code: import React, { Component } from "react"; import "./App.css"; import Slider from "@material-ui/core/Slider"; import Typography from "@material-ui/core/Typography"; class App extends Compo ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...