How to attach id to ng-model dynamically - c#

<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.

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);
}

asp.net core mvc model binding with jquery repeater

I am using jquery repeater in my form to dynamically add only a part of input group to form. I did try but couldn't get inputs bind to model, I went blind.
Here my model.
public class SuggestionCreateEditViewModel
{
public Guid[] DetectionId { get; set; }
public SuggestionCreateEditRepeatedModel[] Repeated { get; set; }
}
public class SuggestionCreateEditRepeatedModel
{
public Guid To { get; set; }
public string Description { get; set; }
public DateTime Deadline { get; set; }
}
Form, I removed a lot of parts of form for brevity
<div class="col-lg-9 col-md-9 col-sm-12">
<select asp-for="DetectionId" asp-items="ViewBag.AllDetections" class="m-bootstrap-select m_selectpicker toValidate"
multiple data-actions-box="true" data-width="100%"></select>
</div>
<div class="col-lg-9 col-md-9 col-sm-12 input-group date">
<input name = "Repeated.Deadline" type="text" readonly class="form-control toValidate dtDueDate" />
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<textarea name = "Repeated.Description" class="form-control toValidate txtSuggestion" type="text" >
</textarea>
</div>
after adding a new repeated section to form and before posting it to server, if I form.serailizeArray() it returns collection like as follows (what jquery form repeater dynamically shape names I believe)
{name: "DetectionId", value: "afca1b82-0455-432e-c780-08d6ac38b012"}
{name: "[0][Repeated.To][]", value: "b1176b82-1c25-4d13-9283-df2b16735266"}
{name: "[0][Repeated.Deadline]", value: "04/04/2019"}
{name: "[0][Repeated.Description]", value: "<p>test 1</p>"}
{name: "[1][Repeated.To]", value: "188806d8-202a-4787-98a6-8dc060624d93"}
{name: "[1][Repeated.Deadline]", value: "05/04/2019"}
{name: "[1][Repeated.Description]", value: "<p>test 2</p>"}
and my controller
[HttpPost]
public IActionResult CreateSuggestion(SuggestionCreateEditViewModel model, IFormFile[] documents)
{...
controller couldn't get Repeated binded, only DetectionId is binded. How should I shape my model to get the data?
Here is a working demo for with jquery.repeater.js, pay attention to this line <div data-repeater-list="Repeated"> which will format the field like name="Repeated[0][Description]"
#model TestCore.Models.SuggestionCreateEditViewModel
#{
ViewData["Title"] = "Contact";
}
<form class="repeater" asp-action="CreateSuggestion" method="post">
<!--
The value given to the data-repeater-list attribute will be used as the
base of rewritten name attributes. In this example, the first
data-repeater-item's name attribute would become group-a[0][text-input],
and the second data-repeater-item would become group-a[1][text-input]
-->
<div data-repeater-list="Repeated">
<div data-repeater-item>
<div class="col-lg-9 col-md-9 col-sm-12">
<select asp-for="DetectionId" asp-items="ViewBag.AllDetections" class="m-bootstrap-select m_selectpicker toValidate"
multiple data-actions-box="true" data-width="100%"></select>
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<textarea name="Description" class="form-control toValidate txtSuggestion" type="text">
</textarea>
</div>
</div>
</div>
<input data-repeater-create type="button" value="Add" />
<input type="submit" value="Submit"/>
</form>
#section Scripts{
<!-- Import repeater js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.js"></script>
<script>
$(document).ready(function () {
$('.repeater').repeater({
// (Optional)
// start with an empty list of repeaters. Set your first (and only)
// "data-repeater-item" with style="display:none;" and pass the
// following configuration flag
initEmpty: true,
// (Optional)
// "show" is called just after an item is added. The item is hidden
// at this point. If a show callback is not given the item will
// have $(this).show() called on it.
show: function () {
$(this).slideDown();
},
// (Optional)
// "hide" is called when a user clicks on a data-repeater-delete
// element. The item is still visible. "hide" is passed a function
// as its first argument which will properly remove the item.
// "hide" allows for a confirmation step, to send a delete request
// to the server, etc. If a hide callback is not given the item
// will be deleted.
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
// (Optional)
// Removes the delete button from the first list item,
// defaults to false.
isFirstItemUndeletable: true
})
});
</script>
}
By the looks of things, the controller cannot bind the repeater properties back to your view model because the naming of the posted content does not match the naming in your view model (as Topher mentioned).
The DetectionId is named correctly though because the name of the property matches and its not an array.
To resolve an array we need to make sure we include the property name in the form as well as an index so that mvc model binding knows where to bind the result to.
With that, can you try changing the format of the name to:
Repeated[0].To
That should match up with your controller and correctly bind.
For more info on binding, please see this.

Can't refresh dropdownlist in asp mvc 4 with chosen 0.9.12

I have few dropdownlist created by using Html.DropDownListFor like:
<div class="control-group">
<label class="control-label" for="inputPropertySurname">
City
<span class="form-required" title="This field is required.">*</span>
</label>
<div class="controls">
#*<input type="text" id="inputPropertySurname">*#
#Html.DropDownListFor(m => m.CityId, vmpa.Cities)
</div>
<!-- /.controls -->
</div>
but it always create a div area after selectbox
<div id="CityId_chzn" class="chzn-containerchzn-container-single
chzn-container-single-nosearch" style="width: 220px;" title="">
<a href="javascript:void(0)" class="chzn-single" tabindex="-1">
<span>Hà Nội</span>
<div><b></b></div>
</a>
<div class="chzn-drop" style="left: -9000px;">
<div class="chzn-search"><input type="text" autocomplete="off">
</div>
<ul class="chzn-results">
<li id="CityId_chzn_o_0" class="active-resultresult-selected" style="">Hà Nội</li>
<li id="CityId_chzn_o_1" class="active-result" style="">Hồ Chí Minh</li>
</ul>
</div>
</div>
i use ajax to get json array and replace new option in json aray to dropdownlist. select box have new option but it still show old option in div id City_chzn. i try many ways jquery but can't refresh it to show new value.
my ajax
<script type="text/javascript">
$(document).ready(function () {
$("#CountryId").chosen().change(function () {
var id = $("#CountryId option:selected").val();
DDLCountryChange(id);
});
});
function DDLCountryChange(id) {
var ddl = $("#CityId");
ddl.chosen();
ddl.prop("disabled", true);
$.ajax({
url: "/Post/GetCityInfoByCountry/" + id,
type: "GET",
dataType: "JSON",
success: function (result) {
ddl.empty();
var str = '';
$.each(result, function (index, value) {
ddl.chosen().append("<option value='" + value['Value'] + "'>" + value['Text'] + "</option>");
ddl.chosen().trigger('listzt:updated');
});
//ddl.prop('disabled', false);
}
});
}
</script>
UPDATE
Now i know why my code create a div. because my template using chosen jquery so it is reason why a div created after select. my chosen ver 0.9.12. i'm using
ddl.trigger('listzt:updated');
but chosen doesn't update new value to display
UPDATE
I have solved my problem. trigger('liszt:updated') not listzt:updated. All my bad :(
Please take a look at this very descriptive and helpful tutorial on how to work with DropDownLists, in an MVC environment, using JQuery and JSON rest services.
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Strangely, the example they are using to make the tutorial, is almost exactly what you're doing here (Country, City, etc)...
Hope this helps!

Programatically change value based on selected item from dropdownlist

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;
}

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