C# razor select2 disable - asp.net-mvc

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});

You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

Related

select2+ASP.NET+MVC set values back to dropdown in edit mode

i am using select2 plugin with ASP.NET+MVC with multiple select option. i am able to save values into database of selected item. now I want to show those values (basically text which associate with those saved ids) into dropdown which has select2 plugin in edit mode.
how can i do that. below is my code.
$(document).ready(function () {
/* below values want to set to dropdown list
var selectedValue1 = '43,48,47,57';
$('#ddlCity1').select2({
multiple: true,
placeholder: "Select City",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
dataType: 'json',
delay: 250,
url: '#Url.Action("GetCityList", "DemoMVC")',
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.City
});
});
return { results: newData };
},
cache: true
},
formatResult: function (element) {
return element.text + ' (' + element.id + ')';
},
formatSelection: function (element) {
return element.text + ' (' + element.id + ')';
},
escapeMarkup: function (m) {
return m;
},
});
$(".city1").on("select2:select", function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
$('.city1').on('select2:unselect', function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
});
//Dropdown with select2 control
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>City</label>
<select id="ddlCity1" class="city1" style="width:500px"></select>
</div>
</div>
</div>

set value to select2 which is retrive from database in ASP.NET MVC

i am using select2 control and i want to display or set value which i retrive from database
how to set value to select2 which is retrive from database in ASP.NET MVC
i am using select2 control and i want to display or set value which i retrive from database
how to set value to select2 which is retrive from database in ASP.NET MVC
<script type="text/javascript">
$(document).ready(function () {
var selectedValue1 = '43,48,47,57';
$('#ddlCity1').select2({
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
dataType: 'json',
delay: 250,
url: '#Url.Action("GetCityList", "DemoMVC")',
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.City
});
});
return { results: newData };
},
cache: true
},
});
$(".city1").on("select2:select", function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
$('.city1').on('select2:unselect', function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
});
</script>
//Dropdown with select2 control
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>City</label>
<select id="ddlCity1" class="city1" style="width:500px"></select>
</div>
</div>
</div>

#Html.EnumDropDownListFor searchable, how to do it?

I am trying to make the helper #Html.EnumDropDownListFor searchable with an input tag on it. That way I can type to search for an item in the huge list. I preferably want to make this hard coded without other plugins. Can someone help me?
Here is the code:
<div>Escolha aqui o banco de sua preferĂȘncia:</div>
#Html.EnumDropDownListFor(model => model.BankPaymentMethods, " ", htmlAttributes: new {#class = "form-control"})
The EnumDropDownListFor helper only generates <select> elements. The closest you can get without a plugin would be an input with a datalist and the list attribute.
Assuming your enum is called BankPaymentMethod and BankPaymentMethods is an IEnumerable of some sort, and your model has a PaymentMethod property:
#Html.TextBoxFor(m => m.PaymentMethod, new { #class = "form-control", list = "payment-methods" })
<datalist id="payment-methods">
#foreach(var method in Model.BankPaymentMethods)
{
<option value="#method">#method</option>
}
</datalist>
For reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist.
Typically its done inside a text box, I guess you can do it inside a Select by appending the value and name also you need to paste your VM or selectList VMModel. I have made some assumptions, code is not tested, but with a couple change and hopefully it will help you.
#Html.TextBoxFor(model => model.BankPaymentID)
#section scripts{
// you can update to the latest version of Jquery-ui, I put in the most compatible version for you
<script src="~/Scripts/jquery-ui-1.15.1.js">script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.15.1/themes/base/jquery-ui.css">
<script>
$(function () {
$("#BankPaymentID").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("Searchable")', // server action
datatype: "json",
data: {
term: request.term // this what you are searching
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
BankPaymentID: val.ID
}
}))
}
})
},
select: function (event, ui) {
$.get("/Home/GetBankPaymentMethods", { BankPaymentID: ui.item.BankPaymentID }, function (data) {
$("#PaymentID").empty();
$.each(data, function (index, row) {
$("#PaymentID").append("<option value='" + row.PaymentID + "'>" + row.PaymentName + "option>")
});
});
}
})
})
script>
}
Controller Searchable Action
public ActionResult Searchable(string term)
{
if (!String.IsNullOrEmpty(term))
{
var list = db.banks.Where(c=>c.PaymentName.ToUpper().Contains(term.ToUpper())).Select(c => new { Name = c.PaymentName, ID = c.BankPaymentID })
.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
else
{
var list = db.banks.Select(c => new { Name = c.PaymentName, ID = c.BankPaymentID })
.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
}

Select2 initSelection element Val

I am using the select2 control on my web aplciation. In the initSelection I am passing the element.val() to a controller but it is null. How would I set element.val() that i want pass to the Url.Action. Is element.val() the correct object that I should be using when I am using a div?
I see the value in Chrome
debugger
view
<div id="guideline-container" style="#(Model.Type == "Guideline" ? "display:block" : "display:none")">
<form id="guideline-form" class="form-horizontal">
<div class="form-group">
<label for="guidelineName" class="col-sm-2 control-label">Guideline</label>
<div class="col-sm-10">
<div id="guidelineName">
#{ Html.RenderAction("Index", "GuidelinesPicklist", new { value = Model.GuidelineId, leaveOutAlgorithmItems = true, separateActiveItems = true }); }
</div>
<div class="guideline-not-selected field-validation-error" style="display: none;">
Guideline is required.
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary modal-submit-btn">Add</button>
<button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</form>
</div>
function
$(this).select2({
placeholder: "#Model.Settings.Placeholder",
//allowClear: true,
ajax: {
url: "#Url.Action("GetPicklistItems")",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: function (params) {
return JSON.stringify({
query: params.term,
args: #Html.Raw(JsonConvert.SerializeObject(#Model.Settings != null ? #Model.Settings.AdditionalArguments : null))
});
},
processResults: function (data, page) {
console.log("processResults");
console.log(data);
var resultData = [];
if (isError(data)) {
showErrorMessage(getErrorMessage(data));
} else {
hideErrorMessage();
mapResultData(data.Result, resultData, 0);
}
return {
results: resultData
};
}
},
templateResult: format,
templateSelection: function(data) {
return data.text;
},
initSelection: function (element, callback) {
//console.log("initSelection");
//var id = $(element).val();
//console.log(id);
var guidelineId = "#Model.Value";
console.log("guidelineId");
console.log(guidelineId);
//console.log("params");
//console.log(params);
//console.log("element object Text");
//console.log(element.text);
debugger;
getAjax("#Url.Action("GetPicklistItem")" + "?value=" + guidelineId, function (result)
{
console.log("Ajax GetPicklistItem");
console.log(result);
debugger;
if (result.Result) {
var data = {};
$.extend(data, result.Result);
data.id = result.Result.Value;
data.text = result.Result.Text;
callback(data);
self.trigger("picklistChanged", data);
} else {
console.log(result);
debugger;
callback ({ id: null, text: "#Model.Settings.Placeholder" })
}
});
},
escapeMarkup: function(m) {
return m;
}
}).on('change', function () {
var data = self.select2('data');
self.trigger("picklistChanged", data);
});
You can get Select2 selected value or text by using the following approaches:
var selectedValue = $('#Employee').val();
var selectedText = $('#Employee :selected').text();
Alternatively you can simply listen to the select2:select event to get the selected item:
$("#Employee").on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}

Trigger change and selection in select2 populated by ajax

I m populating my select2 using ajax with processResults function as in this code,
function PopulateSelect2(sqlclass, ControlID, PlaceHolder) {
$('#' + ControlID).select2({
placeholder: PlaceHolder,
allowClear: true,
theme: "bootstrap",
ajax: {
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
contentType: "application/json; charset=utf-8",
dataType: "json",
//delay: 250,
data: JSON.stringify({ selector: sqlclass, subselector: '' }),
processResults: function (data) {
var parsed = JSON.parse(data.d);
console.log(parsed)
return {
results: parsed
};
}
},
});}
and I call this function in this way,
$(document).ready(function () {
PopulateSelect2("ddl_occupation", "AddrStateID", "Select")
});
I am trying to set the value after by triggering change but its not working
I tried the following,
$('#AddrStateID').val(4).trigger('change.select2');
I managed to trigger selection inside the list but without showing the value in theselectelement control using this code
$("#AddrStateID").select2("trigger", "select", {
data: { id: "4" }
})
is there a way to trigger the selection and show the result in the select control?
So in i worked around it by pre-populating my select control by ajax call but not by using select2 - ajax call
I added the following attributes to each select control
parent="" param="" child="" placeholder="" aval=""
Where,
parent: represents the parent id selector,
param: represents the control's data parameter that I use for ajax call,
child: represents the control's child control id selector,
placeholder: represents the control's placeholder,
aval: represents the control's assigned value in case wanted to be populated and selected because I use my form for storing data and reading data as well.
in the following example I have 3 select cascade controls.
<div class="panel-body">
<div class="col-xs-12">
<div class="form-grobtn row">
<label class="col-sm-2 col-form-label">File Grobtn</label>
<div class="col-sm-10">
<select id="GpId" style="width: 100%"
class="form-control populate" name="GpId" parent="" param="ddl_btnldgp" child="#CatId"
placeholder="File Grobtn..."
aval="">
<option></option>
</select>
</div>
</div>
<div class="form-grobtn row">
<label class="col-sm-2 col-form-label">File Category</label>
<div class="col-sm-10">
<select id="CatId" style="width: 100%"
class="form-control populate" name="CatId" parent="#GpId" param="ddl_btnldcat"
placeholder="Select File Category..."
child="#CatDtlId" aval="">
<option></option>
</select>
</div>
</div>
<div class="form-grobtn row">
<label for="inputPassword3" class="col-sm-2 col-form-label">File Type</label>
<div class="col-sm-10">
<select id="CatDtlId" style="width: 100%"
class="form-control populate" parent="#CatId" param="ddl_btnldcatdtl" child=""
placeholder="Select File Type..."
aval="">
<option></option>
</select>
</div>
</div>
</div>
</div>
<button id="btn" class="btn cUpldBtn btn-success" type="button">
Assign</button>
And Are being populated using this function
function populateddl(ctl) {
var $this = $(ctl);
var parent, param, child, aval
parent = $this.attr('parent');
placeholder = $this.attr('placeholder');
child = $this.attr('child');
$(child).prop("disabled", true);
param = $this.attr('param');
aval = $this.attr('aval');
if (!parent) {
$.ajax({
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
data: JSON.stringify(obj = {
selector: param,
subselector: null
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonData = JSON.parse(data.d);
$this.html('').append('<option>')
$(child).prop("disabled", true)
$this.select2({
data: jsonData,
placeholder: $this.attr('PlaceHolder'),
allowClear: true,
theme: "bootstrap"
});
if (aval) { $this.val(aval).trigger('change'); $this.attr('aval',''); }
},
})
}
$this.change(function () {
if ($this.val() && child) {
$.ajax({
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
data: JSON.stringify(obj = {
selector: $(child).attr('param'),
subselector: $this.val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonData = JSON.parse(data.d);
$(child).html('').append('<option>')
$(child).prop("disabled", false)
$(child).select2({
data: jsonData,
placeholder: $(child).attr('PlaceHolder'),
allowClear: true,
theme: "bootstrap"
});
if ($(child).attr('aval')) { $(child).val($(child).attr('aval')).trigger('change'); $(child).attr('aval', ''); }
},
})
} else {
$(child).html('').append('<option>').prop("disabled", true).trigger('change');
}
})}
Only parents (including childs that are parent to sub select controls) are called using function populateddl(ctl)
in this example I populate as following,
$(document).ready(function () {
populateddl('#GpId');
populateddl('#CatId');
})
In order to assign values, I need to populate and select the value afterwords for child controls,
$(document).ready(function () {
$("#btn").click(function () {
$('#GpId').val(1).attr('aval', '1').trigger('change', 'select2');
$('#CatId').val(2).attr('aval', '2').trigger('change', 'select2');
$('#CatDtlId').val(1).attr('aval', '1').trigger('change', 'select2');
return false;
})
})

Resources