简体   繁体   中英

ASP.Net Core SelectList not displaying selected item

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM