Combining an Editor and Dropdown Feature for a Single Attribute in Asp.Net MVC

How can I implement both an Editor and a Dropdown list for a single field? In the scenario where an agency is not already in the database, the user should be able to enter the agency name. Otherwise, the value should be selected from a dropdown list. I need recommendations on how to achieve this functionality. Specifically, if the first option (Editor) is chosen, the second one (Dropdownlist) should be null. Additionally, if the dropdown list is not selected, I would like to pass the text value entered by the user, but if the dropdown value is chosen, the textbox should remain empty.

        @Html.EditorFor(model => model.AgentName)
        @Html.DropDownListFor(model => model.AgentName, ViewBag.Agency as IEnumerable<SelectListItem>, "Select")

Answer №1

To simplify this, you can use two different properties...

public string ChosenAgent{ get; set; }
public string AgentSelected { get; set; }

In the display section:

@Html.DropDownListFor(model => model.ChosenAgent, ViewBag.Agency as IEnumerable<SelectListItem>, "Select")
@Html.EditorFor(model => model.AgentSelected)

When inserting data, determine which property contains a value....

string.IsNullOrEmpty(model.AgentSelected) ? model.ChosenAgent : model.AgentSelected

Answer №2

By introducing a new field in the Class structure, I made some modifications to the controller and View components, leading me to the solution.

View:

@Html.DropDownListFor(model => model.AgentName, ViewBag.Agency as IEnumerable<SelectListItem>, "Select")
@Html.EditorFor(model => model.AgentNameNew)
@Html.ValidationMessageFor(model => model.AgentName)

Controller:

internationalarrival.AgentName = string.IsNullOrEmpty(internationalarrival.AgentNameNew) ? internationalarrival.AgentName : internationalarrival.AgentNameNew;
db.InternationalArrivals.Add(internationalarrival);
db.SaveChanges();

and In

Model:

public partial class InternationalArrival
{
    public decimal InternationalArrivalId { get; set; }
    public string AgentName { get; set; }

    public string AgentNameNew { get; set; }
    [Required]
    public string AgentCode { get; set; }


    public Nullable<DateTime> ArrivalDate { get; set; }

    [Required]
    public Nullable<int> ForPAX { get; set; }
    [Required]
    public Nullable<int> IndPAX { get; set; }
}

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

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Issue with Angular.forEach loop malfunctioning

Here is the code for my custom filter that includes a parameter called viewbookoption, which is a dropdown value. Depending on the selected value from the dropdown, the data will be displayed in a grid. I have used a forEach loop in this filter, but it see ...

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

Obtain details regarding a worker's collision

This code snippet is being used to manage cluster crashes within a node application cluster.on('exit', function (worker, code, signal) { console.log("error in cluster",worker); console.log("cluster code",code); console.l ...

I can't see the presence of spin.js on my website

I am completely new to Javascript and I'm trying to implement a loading spinner on my website. Whenever users tap the screen, it takes some time to navigate to the desired URL, so we need a spinner to prevent them from tapping repeatedly. I decided t ...

I am looking to adjust/modulate my x-axis labels in c3 js

(I'm specifically using c3.js, but I also added d3.js tags) I have been working on creating a graph that displays data for each month based on user clicks. However, I am facing an issue where the x-axis labels show 0-X instead of 1-X. For instance, ...

The "variable" used in the React app is not defined, resulting in a no

Following the tutorial of Mosh Hamedani, I attempted to create a react-app. You can watch the tutorial here. I followed his instructions exactly as mentioned. I encountered an issue when trying to pass an argument named product to a function called on on ...

Encountering an issue with the v-carousel component from Vuetify: receiving a 'Cannot read property 't' of undefined' error message

Currently, I am trying to create an image carousel using Laravel along with Vue/Vuetify. The issue lies in the fact that the Vuetify v-carousel and v-carousel-item components are not rendering properly due to the error mentioned in the title. I have alrea ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Metronome in TypeScript

I am currently working on developing a metronome using Typescript within the Angular 2 framework. Many thanks to @Nitzan-Tomer for assisting me with the foundational concepts, as discussed in this Stack Overflow post: Typescript Loop with Delay. My curren ...

Build a flexible Yup validation schema using JSON data

I am currently utilizing the power of Yup in conjunction with Formik within my react form setup. The fields within the form are dynamic, meaning their validations need to be dynamic as well. export const formData = [ { id: "name", label: "Full n ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

Display additional fields based on a condition in ASP.NET Core 6.0 MVC for a Yes/No input

If a user enters either Yes or No in a specific field, I want to display additional fields that need to be filled based on their choice. <div class="col-6"> <label for="Renda Bruta">Demonstrativo do Ano</label> ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...

Connecting Vue component data to external state sources

I am facing a challenge with integrating a Vue component into a large legacy system that is not based on Vue. This component retrieves data through AJAX requests and displays information based on an array of database record IDs, typically passed at page lo ...

Is there a way to place two input fields from different forms side by side on the same line?

Here are two forms extracted from an html page: <form method="get" action="search/s" id="number"> <div style="text-align: center;"> <input type="text" id="regNo" name="regNo" size="30" maxLength="50" > or ...

utilize jQuery and AngularJS to transform a JSON object into a nested JSON structure

Is there a way to convert my current JSON file into a nested JSON structure like the one below? I've attempted various methods (How to convert form input fields to nested JSON structure using jQuery), but I'm not achieving the desired outcome. Ca ...

The lack of synchronization between the updated state in one function and its counterpart is causing discrepancies, resulting in the incorrect information being sent to the API

Whenever I press the following button: <Button onClick={(e) => { addToCard(item); handleprisma(); }} > add to cart </Button> This function is meant to add the item to my shopping cart: const addToCard = (item) => { co ...

How can I showcase images stored in an array using JavaScript?

I am currently developing a role-playing game (RPG). In order to enhance the gameplay experience, I am trying to implement a for loop that will dynamically generate buttons on the screen. Here is the code snippet I have created so far: $(document).ready(f ...