0

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))
  • Are you sure your source query isn't returning an IQueryable? Have you tried adding .ToList() and then testing your code? – eVolve Jan 23 '20 at 14:50
  • I tried your suggestion. Since the same routine works when I return to the page, I did not expect success and did not experience success. While the list of schools always comes from the DB (and is otherwise rendered correctly), the selected value comes from HttpContext.Session instead of the database when the list is correctly set (clicking the 'Prev' button in the context of the wizard), I am not yet inclined to consider that the immediate source of the value is relevant. – michaelcoder Jan 23 '20 at 17:24

1 Answers1

0

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!

OO7
  • 660
  • 4
  • 10
  • Thanks for the feedback. While the ID identifiers look like numbers, they are defined as varchar in the SQL Server DB and appear everywhere while debugging with leading zeroes and quotes. I made an earlier change from nvarchar to varchar ro account for character width/size but to no avail. – michaelcoder Jan 23 '20 at 17:13
  • You are always welcome. Well, No problem with formatted string varchar. Because you can use PadLeft() method from String. I will edit my answer, pls to check soon. – OO7 Jan 23 '20 at 18:05