Binding Selected Item on Page Load

Hi there,

I am fetching a record from the DB and displaying it in a razor view. The text fields bind successfully, however the dropdown lists do not - they do not auto-select the item in the dropdown list that matches the DB record.

I know in plain MVC, when building a List<SelectListItem>, you can set the Selected property to true and when the view renders, this item will be auto-selected in the list.

Is this possible?

Backend Code:

var user = await _dbContext.Users.AsNoTracking().FirstOrDefaultAsync(x => x.Id == query.Id, cancellationToken);

var contractTypes = _dbContext.ContractTypes
                                    .AsNoTracking()
                                    .ToList()
                                    .Select(x => new SelectListItem
                                    {
                                        Text = x.Description,
                                        Value = x.Id.ToString(),
                                        Selected = x.Id == user.ContractTypeId
                                    });
return contractTypes;

View:
<div class="mt-2">
    @(
        Html.EJS()
            .DropDownList("contractTypes")
            .DataSource(Model.ContractTypes)
            .Fields(new DropDownListFieldSettings { Text = "Text", Value = "Value" })
            .Placeholder("Employment Contract Type")
            .HtmlAttributes(new Dictionary<string, object>
            {
                { "name", "User.ContractTypeId" }
            })
        .Render()
    )
</div>

Result:


Kind regards,
Charles

3 Replies 1 reply marked as answer

SP Sureshkumar P Syncfusion Team August 11, 2020 12:38 PM UTC

Hi Charles, 
 
Greetings from Syncfusion support. 
 
Before proceeding your query, can you please provide the information below to help us understand the requirement further? 
1.      Requirement to display a screenshot / video  
2.      Elaborate more details about the issue 
Regards, 
Sureshkumar P 
 



CT Charles Trent August 11, 2020 12:51 PM UTC

Hi Sureshkumar,

Thanks for reaching out. Basically, I'm wanting to know, when a page loads, how would I set an item in a dropdown list to be auto-selected?
In the screenshot below, I'm populating dropdown lists with values from the database, and I'm attempting to try and have a value auto-selected in the dropdown using the logic in the backend (Selected = x.Id == user.ContractTypeId)

When this page loads, it should be auto-selecting an item in the dropdown list but it's not.

Kind regards,
Charles


SP Sureshkumar P Syncfusion Team August 12, 2020 10:30 AM UTC

Hi Charles, 
 
Thanks for your update. 
 
Based on your shared information, we suspect that you want to render the component with preselected value. So, we suggest you update the value property when rendering the component to achieve your requirement.  
 
Regards, 
Sureshkumar P 


Marked as answer
Loader.
Up arrow icon