ASP.Net Core SelectList not displaying selected item - asp.net-core

Using ASP.Net core 2.2 in VS 2017 (MVC):
I have a wizard based screen that has a drop down list of Organizations.
When I load a record from the Database, I want to set the select list to the values in the DB.
Spoiler alert: The specified Item is not selected when the page is initially displayed.
When the item is manually selected, and the ‘Next’ button is clicked and then the Prev button is clicked, returning us to the first page, the item is selected just as I intend.
None of the methods below set the ‘Selected’ property of the selected item (“0403”) when loading the Model in the controller for the first display.
The compare in Method 2 never evaluates to true even though I can see the compared values are equal while debugging.
Method 3 does not find the item even though I can see the compared values are equal while debugging
Method 4 does not find the item even though I can see the compared values are equal while debugging
This is all happening in the Controller, so please do not suggest changing the name of the dropdown in the View.
**Org table
ORG ID OrgName**
0004 Org 4
0007 Org 7
0008 Org 8
0403 Org 403
This is my source query:
var orgsQuery = from s in _context.Orgs
orderby s.OrgID
select s;
These are the various ways I have tried building the select List in the Controller:
1).
SelectList oList = new SelectList(orgsQuery.AsNoTracking(), "OrgID", "OrgName", selectedOrg);
2).
List<SelectListItem> oList = new List<SelectListItem>();
foreach ( var item in OrgsQuery)
{
oList.Add(new SelectListItem()
{
Text = item.OrgName,
Value = item.OrgID,
Selected = (item.OrgID == (string)selectedOrg ? true : false)
});
}
3).
if (selectedOrg != null)
{
oList = new SelectList(OrgsQuery.AsNoTracking(),"OrgID", "OrgName", OrgsQuery.First(s =>
s.OrgID == (string)selectedOrg));
}
else
{
oList = new SelectList(OrgsQuery.AsNoTracking(), "OrgID", "OrgName", selectedOrg);
}
4).
SelectList oList =
new SelectList(_context.Org.OrderBy(r => r.OrgID),
_context.Org.SingleOrDefault(s => s.OrgID == (string)selectedOrg))

Well, assume that selectedOrg type is numeric, than it should be convert to formatted string by following the OrgID format:
var formattedSelectedOrg = String.Format("{0:0000}", selectedOrg);
Or
// if selectedOrg is nullable numeric type
var formattedSelectedOrg = selectedOrg?.ToString("0000");
// if selectedOrg is base numeric type
var formattedSelectedOrg = selectedOrg.ToString("0000");
// if selectedOrg is String type (nullable)
var formattedSelectedOrg = selectedOrg?.Trim().PadLeft(4, '0');
Or
var number;
var formattedSelectedOrg =
String.Format("{0:0000}", Int32.TryParse(selectedOrg?.Trim(), out number) ? number : 0);
So it would be comparable when applied to your codes:
// assume selectedOrg is base numeric type
Selected = item.OrgID == selectedOrg.ToString("0000")
Or
// if selectedOrg is String type (nullable)
Selected = item.OrgID == selectedOrg?.Trim().PadLeft(4, '0')
Or
// if you prefer to use predefined formatted string
Selected = item.OrgID == formattedSelectedOrg
And
// assume selectedOrg is base numeric type
s => s.OrgID == selectedOrg.ToString("0000")
Or
// if selectedOrg is String type (nullable)
s => s.OrgID == selectedOrg?.Trim().PadLeft(4, '0')
Or
// if you prefer to use predefined formatted string
s => s.OrgID == formattedSelectedOrg
Check this out:
Custom numeric format strings
String.PadLeft Method
Also this important briefcase:
Pad left with zeroes
Hope this could helps. Enjoy your coding!

Related

Get the value of selectbox in cocoascript

I'm developing a sketch plugin. In the modal window I'm using to get user input there is a select. I can access the value of textField but I can't access value of the select.
Here is where I create the select:
var chooseFormatOptions = ['.png', '.jpg', '.pdf'];
var chooseFormatSelect = NSComboBox.alloc().initWithFrame(NSMakeRect(0, 250, viewWidth, 30));
chooseFormatSelect.addItemsWithObjectValues(chooseFormatOptions);
Here is where I try to get the combo box value
if (response == "1000"){
var projectName = projectField.stringValue();
var deviceName1 = firstDevicefield.stringValue();
var deviceDim1 = firstDimfield.stringValue();
var deviceName2 = secondDevicefield.stringValue();
var deviceDim2 = secondDimfield.stringValue();
var format = chooseFormatSelect.objectValues.indexOfSelectedItem(),
//var scale = chooseScaleOptions.stringValue();
//var pathOption = choosePathOptions.stringValue();
}
The error that it gives me when I run the plugin (if response == 1000) is: can't find variable chooseFormatSelect.
Do you know why I can get values of input fields (so it can find variables) but not that of the select one?
What about access text field 'text' variable while observing changes?
You may find this link helpfull (to add observe).
For NSComboBox follow this
Simply implement delegate then access value through following method

Need to display first n items from each category in Razor using Umbraco

I am new to Umbraco. I have a list of items in a content named Videos. Each item have a specific category. I need to retrieve 'n' number of items from each category. Some one please help. Also am using MixItUp jquery plugin to display the items.
// this will bring up all items from the list
var items = Umbraco.TypedContent(Model.Content.Id).Children.Where(x => x.DocumentTypeAlias == "videoItem" && x.IsVisible());
// Here am trying to bring 5 items under category "Testimonial"
var allItems = items.Where(x => x.GetPropertyValue("category") == "Testimonial").Take(5);
But I didn't found any output. Please help.
Your second line of code should read:
var allItems = items
.Where(x => x.GetPropertyValue<string>("category") == "Testimonial")
.Take(5);
Rather than simply cast the result to string, this will try and convert the object to the desired type if it isn't already - see here.
If you're using the new ModelsBuilder (which is awesome) you also have the option of strongly typing the whole process.
var items = Model.Content.Children<VideoItem>().Where(x => x.IsVisible());
var allItems = items.Where(x => x.Category == "Testimonial").Take(5);

AJAX filled pulldown shows 5 identical options when there are 5 different options in database

Scratching head here. I've got a pulldown and if I query it in SQL Server Manager Query Window I get 5 different values (these are sample points for a water system).
However, when the pulldown loads, there are 5 options of the first value. Can someone see something I can't?
I narrowed it down to the code below because I held my cursor over "results" which was the final step in my Controller's code, and it showed 5 items all of the same value:
else if ((sampletype == "P") || (sampletype == "T") || (sampletype == "C") || (sampletype == "A"))
{
var SamplePoints = (from c in _db.tblPWS_WSF_SPID_ISN_Lookup
where c.PWS == id && c.WSFStateCode.Substring(0, 1) == "S"
select c).ToList();
if (SamplePoints.Any())
{
var listItemsBig = SamplePoints.Select(p => new SelectListItem
{
Selected = false,
Text = p.WSFStateCode.ToString() + ":::" + p.SamplePointID.ToString(),
Value = p.WSFStateCode.ToString()
}).ToList();
results = new JsonResult { Data = listItemsBig };
}
}
return results ;
}
I have had a similar problem in nHibernate, it was caused by how I defined my primary keys/foreign keys in the ORM, leading to a bad join and duplicate values.

Refresh a dijit.form.Select

First, you have to know that I am developing my project with Struts (J2EE
Here is my problem :
I have 2 dijit.form.Select widgets in my page, and those Select are filled with the same list (returned by a Java class).
When I select an option in my 1st "Select widget", I would like to update my 2nd Select widget, and disable the selected options from my 1st widget (to prevent users to select the same item twice).
I succeed doing this (I'll show you my code later), but my problem is that when I open my 2nd list, even once, it will never be refreshed again. So I can play a long time with my 1st Select, and choose many other options, the only option disabled in my 2nd list is the first I've selected.
Here is my JS Code :
function removeSelectedOption(){
var list1 = dijit.byId("codeModif1");
var list2 = dijit.byId("codeModif2");
var list1SelectedOptionValue = list1.get("value");
if(list1SelectedOptionValue!= null){
list2.reset();
for(var i = 0; i < myListSize; i++){
// If the value of the current option = my selected option from list1
if(liste2.getOptions(i).value == list1SelectedOptionValue){
list2.getOptions(i).disabled = true;
} else {
list2.getOptions(i).disabled = false;
}
}
}
Thanks for your help
Regards
I think you have to reset() the Select after you've updated its options' properties. Something like:
function removeSelectedOption(value)
{
var list2 = dijit.byId("codeModif2"),
prev = list2.get('value');
for(var i = 0; i < myListSize; i++)
{
var opt = myList[i];
opt.disabled = opt.value === value;
list2.updateOption(opt);
}
list2.reset();
// Set selection again, unless it was the newly disabled one.
if(prev !== value) list2.set('value', prev);
};
(I'm assuming you have a myList containing the possible options here, and the accompanying myListSize.)

SharePoint 2010 - Custom calculated column

In a document library I need a custom calculated column, because the default Excel formula don't provide the functionality I need.
I created a custom field inheriting from SPFieldText, that I then could customize at will. The question is: how is it possible, from my custom field, to access the content values of the other fields of the document library?
In other world, in the overriden GetValidatedString method, how can I return a value that is dependent upon values from other fields, for the same record? How to implement getFieldValue() , below:
public class MyCustomField : SPFieldText
{
....
public override string GetValidatedString(object value)
{
string value1 = getFieldValue("Column-Name1");
string value2 = getFieldValue("Column-Name2");
return value1 + ", " + value2; // any arbitrary operation on field values
}
}
Thanks!
You should be able to grab other values from the form using the Item property of the FormComponent or the Item property of the ItemContext.
Either of these should work from the FieldControl class:
Code Snippet
if ((this.ControlMode == SPControlMode.New) || (this.ControlMode == SPControlMode.Edit))
{
object obj = this.Item["Name"];
if (obj != null)
string name = obj.ToString();
object obj2 = base.ItemContext.Item["Name"];
if (obj2 != null)
string name2 = obj2.ToString();
}
where "Name" is the internal name of the field that you wish to retrieve.