Programatically change value based on selected item from dropdownlist - c#

I'm still getting used to changing over from asp.net to asp.net mvc and I know that it doesn't use on action commands but I'm trying to change the text of a label based on when a user selects an item from a dropdownlist. I'm really not sure where to start :(

You can easily get this done using some jQuery, here I made a Fiddle for you.
Below is how you HTML should look like, incase you are using pure HTML in your views or even if you are using #Html.LabelFor or #Html.DropDownListFor
HTML
<label id="myLabel">Select a fruit:</label>
<select id="fruitSelector">
<option val="">None</option>
<option val="apple">apple</option>
<option val="orange">orange</option>
<option val="mango">mango</option>
</select>
jQuery
$("#fruitSelector").change(function(){
$("#myLabel").text("Fruit has been selected");
});
Related help
https://stackoverflow.com/a/16828702/1182982
https://stackoverflow.com/a/14606324/1182982

Here is the simple example using jquery
#Html.DropDownList("State", ViewBag.StateName as SelectList,
"Select a State",
new { id = "State" })
<label id="lbl1"></label>
<script type="text/jscript">
$(function () {
$('#State').change(function () {
$('#lbl1').text($('#State').val());
});
});
</script>

You can try something like this
<label id="item">Selected Item: </label>
<select id="selector">
<option value="">None</option>
<option value="JS">JavaScript</option>
<option value="aspnet">Asp.net</option>
<option value="mvc">Asp.Net MVC</option>
</select>
<label id="result"></label>
$("#selector").change(function()
{
$("#result").text($(this).val());
});
http://jsfiddle.net/PLbnS/

To start with, your aspx should look like this:
<asp:DropDownList AutoPostBack="true" runat="server" ID="myListDropDown"
CssClass="text" OnSelectedIndexChanged="myListDropDown_Change" />
And your code-behind file:
private void myListDropDown_SelectedIndexChanged(object sender, System.EventArgs e)
{
//put your code here
}

Simple :
Write this code in your SelectedValueChanged Event of dropdownlist :-
private void dropdownlist_SelectedValueChanged(object sender, EventArgs e)
{
dropdownlist.Items["abc"]=label.text;
dropdownlist.Items["xyz"]=label.text;
}

Related

I want autopostback on dropdownlist on Razor page not MVC

I want autopostback on dropdownlist on Razor page not MVC
I have this code but it not working, the intention is to call what has been select immediately for another process.
<select id="ddlDList" class="form-control" name="PredefineID" asp-items="#Model.ListModes" new { onchange = "DoPostBack();" }">
<option value="0">Please select</option>
</select>
.......
public string DoPostBack()
{
…..
return listdefine;
}
You can try to use ajax to get data from razor page handler:
html:
<select id="ddlDList" class="form-control" name="PredefineID" asp-items="#Model.ListModes" onchange=DoPostBack()>
<option value="0">Please select</option>
</select>
js:
<script>
function DoPostBack() {
$.ajax({
type: "GET",
url: "?handler=DoPostBack&&PredefineID=" + $("#ddlDList").val(),
success: function (listdefine) {
//get listdefine here
}
});
</script>
handler in cshtml.cs file:
public JsonResult OnGetDoPostBack(int PredefineID) {
...
return new JsonResult(listdefine);
}

Get Select2 Selected Value From Code Behind ASP .Net Web Form

I have a problem with Select2 V 4.02
Here is my code
<select id="MySelect" class="form-control" runat="server" ClientIDMode="static">
<option></option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<asp:Button Text="Show Select2 Result" runat="server" ID="btnShow" OnClick="btnShow_Click"/>
jQuery:
$('#MySelect').select2({
placeholder: "-Select-"
});
My question is:
Can I get the "MySelect" selected value from ASP .Net Code behind?
I tried this code from code behind asp .net webform
protected void btnShow_Click(object sender, EventArgs e)
{
Response.Write(MySelect.Value);
}
But it returns empty string.
you can use standard hidden field like this :
<asp:HiddenField ID="hf1" runat="server" />
then in your JavaScript :
$('#MySelect').on('change', function () {
$('#<%=hf1.ClientID%>').val($(this).val());
}
in your code behind :
protected void btnShow_Click(object sender, EventArgs e)
{
Response.Write(hf1.Value);
}
i hope work for you

How to attach id to ng-model dynamically

<select class="form-control" select-multiple-picker multiple data-max-options="2" ng-model="userDetails.ClinicalRoles" name="createUserSelectClinicalRoles" id="createUserSelectClinicalRoles">
<option ng-repeat="role in clinicalRole" value="{{role.Description}}">{{role.Description}}</option>
</select>
Here I am getting data from server to list, I am only showing {{role.Description}} to user, but when I submit I need to attach role.id and role.Description to ng-Model for calling API.
You can do this with ng-options and select as: https://docs.angularjs.org/api/ng/directive/ngOptions
Don't use ng-repeat for that. Use ng-options instead.
Try this-
<select class="form-control" select-multiple-picker multiple data-max-options="2" ng-model="userDetails.ClinicalRoles" name="createUserSelectClinicalRoles" id="createUserSelectClinicalRoles"
ng-options="role.id as role.Description for role in clinicalRole">
</select>
If you want to select both at a time. Then you can use a trick. Add ng-change attribute in select and pass that selected role.id as it's model in a function.
HTML
<select class="form-control" select-multiple-picker multiple data-max-options="2" ng-model="userDetails.ClinicalRoles" name="createUserSelectClinicalRoles" id="createUserSelectClinicalRoles"
ng-options="role.id as role.Description for role in clinicalRole"
ng-change="setDescription(role)">
</select>
JS
$scope.lastSelectedDesc = {};
$scope.setDescription(role){
$scope.lastSelectedDesc = role;
}
Simply do this.
You can save complete object in ng-model instead of single property.
HTML :-
<div data-ng-app="myApp" data-ng-controller="Ctrl" style="margin-top:40px">
<div>
<select class="form-control" id="Region" data-ng-model="selectedValue" data-ng-options="value.Desc for value in values track by value.id">
<option value=''>Select</option>
</select>
</div>
<div>
Selected Option Label : {{selectedValue.label}}<hr/>
Selected Option Id : {{selectedValue.id}}<hr/>
Selected Option Desc : {{selectedValue.Desc}}<hr />
</div>
</div>
Javascript :-
<script type="text/javascript">
var IsApp = angular.module('myApp', []);
IsApp.controller('Ctrl', function ($scope, $http) {
$scope.values = [{
id: 1,
label: 'aLabel',
Desc: 'Desc-aLabel'
}, {
id: 2,
label: 'bLabel',
Desc: 'Desc-bLabel'
}];
});// End of controller
</script>
While submitting you can pass selectedValue.id and selectedValue.Desc.

HTML form submit, .Net, save fields as XML

We have an HTML page with an form on it.
We are prepopulating a form from an XML file using jQuery AJAX.
We would like the form, on submit, to save over our default.xml file. Most likely we will use ASP.Net as our server side.
Our question would be, what would the ASP.Net/C# look like in order to save the info in put in the form and save over our XML file.
Thanks in advance.
EDIT
This is our example:
<option id="timeBlockOne">
<select>12:00</select>
<select>1:00</select>
</option>
<option id="titleBlockOne">
<select>Title One</select>
<select>Title Two</select>
</option>
<option id="titleBlockTwo">
<select>Title three</select>
<select>Title Four</select>
</option>
<option id="timeBlockTwo">
<select>12:00</select>
<select>1:00</select>
</option>
...etc up to 10 blocks.
<button action="Post">Submit</button>
Desired XML output.
<main>
<itemOne>
<timeBlockOneValue>Value selected from form</timeBlockOneValue>
<titleBlockOneValue>Value Selected from form</titleBlockOneValue>
</itemOne>
<itemTwo>
<timeBlockTwoValue>Value selected from form</timeBlockTwoValue>
<titleBlockTwoValue>Value Selected from form</titleBlockTwoValue>
</itemTwo>
...etc
</main>
Hopefully this helps out with my question.
Alright, here is a possible way to get you on the right track, please let me know if this is not clear.
JavaScript:
function GetXMLButton() {
var xml = "<main>";
var i = 1;
// Loop for each OPTION element in the myForm div
$("#myform select").each(function() {
// Get value of selected option.
var selectedValue = $(this).val();
xml = xml + "<item_" + i + "><" + this.id + ">" + selectedValue + "</" + this.id + "></item_" + i + ">";
i++;
});
xml = xml + "</main>";
// Call C# WebMethod to save into xml file
PageMethods.SaveXMLFile(xml);
}
ASPX: Make sure to set EnablePageMethods = true in the ScriptManager object. Also I think you might have switched your OPTION and SELECT tags, check your code, it should be SELECT then OPTION tag.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<div id="myForm">
<select id="timeBlockOne">
<option selected>12:00</option>
<option>1:00</option>
</select>
<select id="titleBlockOne">
<option>Title One</option>
<option selected>Title Two</option>
</select>
<select id="titleBlockTwo">
<option selected>Title three</option>
<option>Title Four</option>
</select>
<select id="timeBlockTwo">
<option>12:00</option>
<option selected>1:00</option>
</select>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="button1" runat="server" Text="Get XML" OnClientClick="return GetXMLButton();" />
C# Code-Behind:
You need to reference the following:
using System.Web.Services;
Then add the following method and make sure you put [WebMethod] before method declaration:
[WebMethod]
public static void SaveXMLFile(string formXMLData)
{
// Put your code to convert formXMLData string to an XML File and save/upload on/to server
}

How to remove an item in DropDownList in ASP MVC using JavaScript

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
In a view, I have a DropDownList, a button.
How can I remove an item from the DropDownList for each click of the button.
I try to use javascript, but I think that's not working because when I click on the button, nothing happens.
This is the code :
<%:Html.Label("Poste :")%>
<%:Html.DropDownListFor(
model => model.SelectedPoste,
Model.PostesItems,
new { #id = "poste" })%>
<div>
<input type="submit"
value="Enregistrer"
id="btnSave"
onclick="remove()" />
</div>
<script type="text/javascript">
function remove() {
var rm = document.getElementById('btnSave');
var poste = document.getElementById('poste');
poste.removeItem();
}
</script>
using jQuery
<select id="poste">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<input type="button" id="btnSave" value="Remove current item" />
<script type="text/javascript">
$(function () {
$('#btnSave').click(function () {
$('#poste option:selected').remove();
return false;
});
});
</script>
EDIT: binding the click event using jQuery
The generated HTML will give the select element an ID of "SelectedPoste", not "poste" as you are attempting to set.
Use remove to remove an item.
Change your javascript to be:
var poste = document.getElementById('SelectedPoste');
poste.remove(poste.selectedIndex);
Edit: The generated HTML for the select will be:
<select id="poste" name="SelectedPoste">...</select>
Either of these two lines will get that elements:
var poste = document.getElementById('poste');
or
var poste = document.getElementById('SelectedPoste');
(Atleast in IE10)
Then to remove the selected item from the list, do:
poste.remove(poste.selectedIndex);
This does not remove the button :)
Edit 2: Like Dimitar's answer, you need to change your function name from remove to something else.
Once you do that, my code above works in IE and Chrome.
Using vanilla JavaScript you can do:
<script type="text/javascript">
function removeOption() {
var posteElement = document.getElementById('poste');
var currentIndex = posteElement.selectedIndex;
posteElement.removeChild(posteElement[currentIndex]);
return false;
}
</script>
That's all you need. Also make sure you rename your function to anything other than remove():
<input type="submit"
value="Enregistrer"
id="btnSave"
onclick="removeOption()" />
Check out this (not very nice inline-fiddle).
However I'd strongly suggest at least looking into a library such as jquery, (this would be much easier than with vanilla.js). Check out Andre's answer.
Try this:
$("#poste option[value='X']").each(function() {
$(this).remove();
});
Or to be more terse, this will work just as well:
$("#poste option[value='X']").remove();
Example:
$("#btnSave").click(function(){
$("#poste option[value='X']").remove();
});
Remember to use JQuery :)

Categories