AngularJS enables seamless two-way data binding with DropDownList in the Model-View-Controller (M

As a beginner in AngularJS, I am currently experimenting with implementing 2-way data binding for the Gender Dropdown menu similar to what I have done with textboxes.

Below is a snippet of code for the dropdown control:

<div class="form-group">
    @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.Gender, new List<SelectListItem> {
             //new SelectListItem { Text="Male", Value="M" },
             //new SelectListItem { Text="Female", Value="F" }
             new SelectListItem { }
        }, new { @class = "form-control", @ng_model = "gender", @ng_options="gender" })
    </div>
</div>

var myapp = angular
.module("myModule", [])
.controller("mycontroller", function ($scope) {
    

    var user = {
        loginid : "Login ID",
        fname : "Enter First Name",
        lname: "Enter Last Name",
        gender:"Male"
        
        
    };
    $scope.user = user;
    $scope.genders =
    [
        { Value: "M", name: "Male" },
        { Value: "F", name: "Female" }
    ];

        
});

The current JavaScript file handles all bindings successfully except for the issue with the gender dropdown section.

Answer №1

Initially, I would advise against implementing this in the Razor way, especially if all your dropdown values originate from your Angular controller. However, here's some code to assist you:

Option 1:

@Html.DropDownListFor(model => model.Gender, new List<SelectListItem>(), new { @class = "form-control", @ng_model = "gender", @ng_options = "item as item.name for item in genders track by item.value" })

Option 2:

<select name="Gender" ng-options="item as item.name for item in genders track by item.value" ng-model="gender"></select>

Note:

$scope.genders =
[
    { value: "M", name: "Male" },
    { value: "F", name: "Female" }
];
  1. Please note that I changed "Value" to lowercase in item.value, so you may need to adjust your gender value property to lowercase or change item.Value to uppercase.
  2. You can utilize any term other than "item" to refer to your collection; further details can be found in the angular document here.

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

Tips for concealing the "maxlength" attribute in HTML

Here is the code snippet I currently use on a signup and login form to restrict users from entering more than a specified number of characters: $( "#limit1" ).attr('maxlength','11').on('input', function() { if ($(this).val(). ...

What is the optimal method for saving and organizing data in SQL?

I currently have a MySQL table containing data that is displayed in an HTML table. Using JavaScript and drag & drop functionality, I am able to locally sort this table. My question is, what is the most effective method for saving these sorting changes? W ...

PHP variable not receiving Ajax variable

As a beginner in Ajax and jQuery, I am learning through Stack Overflow and online tutorials. Please be considerate of my novice level as you read and potentially offer advice on my post. I have successfully created a form that displays a message upon subm ...

Ways to trigger javascript following each ajax or complete request

I have a jQuery function that attaches a click event to specific elements, as shown below. $(".alert-message .close").click(function(e) { $(this).parent().fadeTo(200, 0, function() { $(this).slideUp(300); }); e.preventDefault(); }) ...

Preventing the use of the <select> tag in JavaScript

As a beginner in JavaScript, I thought it would be a great idea to work on a simple Calculator project. I've already tackled the basics like addition and subtraction, but now I'm contemplating adding a squareroot function to it. The design incl ...

I encountered a problem while attempting to update the browser URL using pushState() in my Angular application

Whenever I try to change the browser URL while a bootstrap modal is open in my AngularJS application, I utilize the pushState() function. This does successfully change the URL, but unfortunately, it results in the following error being thrown: Uncaught ...

When scrolling down, the popup window shifts its position

I have implemented a popup window which displays a list on hover. It works perfectly on the default page, but when I scroll down, the popup also moves with the scrollbar. Below is the HTML code that creates the hidden popup list initially and shows it on ...

Having trouble resolving the dependency tree within react-navigation-stack

Trying to understand navigation in React-native and attempting to execute the following code: import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; import {createAppContainer} from 'react-nav ...

What is the best way to retrieve JSON data in a React application?

useEffect(async () => { const fetchPostData = async () => { const response = await axios("") setPosts(response.data) } fetchPostData(); }, []) Rendering : posts.map(post => <li>{post.name} ...

Using Laravel to submit a form with identical input names via AJAX

Seeking assistance with my ajax function. A form I have is submitting data with the same input name. Without using JavaScript, I can insert multiple input data with the same name easily, Here is the structure of the submitted data {"_token":& ...

Having trouble with my React Next app, it's giving me an error stating "window is not defined

Currently, I am developing in Next.js using React components and encountering an issue. I keep receiving a ReferenceError: window is not defined error in react-location-picker. If you need to check out the package, here is the link: react-location-picker ...

Generating interactive child posts for a specialized post type in WordPress

I am currently in the process of planning a simple plugin and am searching for ideas on how to add subposts (child) for posts in WordPress directly on the post creation page. I would like to incorporate a form with two fields, title and content, and have ...

Display an icon within an HTML element when the content inside it exceeds its boundaries

Looking to display a copy to clipboard icon when the content inside a div overflows I am using ngFor to iterate through four divs, and if any of those divs is overflowing, I want to show an icon specific to that respective div. <div *ngFor div of Four ...

Ever wonder what goes on behind the scenes when you press a button before the Javascript method is carried out

My web application is built using ASP.NET MVC 4, jQuery, and Telerik's Kendo controls. Within my webpage, I have the following code snippet: <input id="cmdSaveToFile" title="Save To File" class="button" type="button" value="Save To File" onclick= ...

Discovering nearby intersections within 2 sets of arrays

Imagine having these two arrays: var a = [126, 619, 4192, 753, 901]; var b = [413, 628, 131, 3563, 19]; Is there a way to identify elements in both arrays that are close to each other by a certain percentage? Let's say we have the following functio ...

Guide on launching a mobile application upon clicking a button in a mobile browser (with the assistance of JavaScript/React) [Utilizing Deep Linking]

My goal is to create a functionality where, on a mobile browser, when the user clicks on a button: If the app is already installed on the user's mobile device, it should open up. If the app is not yet installed, I aim to redirect the user to the appr ...

Turn off the perpetual active mode

I have a situation where a link maintains its active state after being dragged and released. This is causing an issue that I need to address. For example, you can see the problem here: http://jsfiddle.net/Ek43k/3/ <a href="javascript:void(0);" id="foo ...

"Passing an Empty String as Input in a NodeJS Application

app.post('/register',function(req,res){ var user=req.body.username; var pass=req.body.password; var foundUser = new Boolean(false); for(var i=0;i<values.length;i++){ //if((JSON.stringify(values[i].usernames).toLowerCase==JSON. ...

What is the best way to incorporate a CSS transition without any dynamic property changes?

Is there a way to add a transition effect to a header when its size changes without a specified height value in the CSS? The header consists of only text with top and bottom padding, so as the text changes, the height adjusts accordingly. How can I impleme ...

I am experiencing an issue where the position of the value in the returned response array keeps changing after an Ajax request is made. How can

I am currently using a script that sends an array of numbers through Ajax to a web server. These numbers are then used to query a database, and the corresponding values from the table are sent back. I then display these values in respective divs within my ...