|
<EditForm Model="@model"> <SfDropDownList TValue="string" TItem="Countries" CssClass="@Validate" Width="200px" ShowClearButton="true" Placeholder="e.g. Australia" DataSource="@Country">
<DropDownListFieldSettings Text="Name" Value="Code"></DropDownListFieldSettings>
<DropDownListEvents TValue="string" ValueChange="OnChange"></DropDownListEvents>
</SfDropDownList>
</EditForm>
public void OnChange(ChangeEventArgs<string> args) {
if (args.Value == null)
{
this.Validate = "e-error";
}
else
{
this.Validate = "e-success";
}
}
|
|
|
|
|
Hello,
can you please give me a sample where the TValue is an Int ? and dropVal is type int ? It does not seems to work with type int
|
<EditForm Model="@model">
<DataAnnotationsValidator />
<SfDropDownList TValue="int?" TItem="Countries" Width="200px" ShowClearButton="true" @bind-Value="@model.dropVal" Placeholder="e.g. Australia" DataSource="@Country">
<DropDownListFieldSettings Text="Name" Value="Code"></DropDownListFieldSettings>
</SfDropDownList>
<ValidationMessage For="() => model.dropVal" />
<SfButton CssClass="e-small e-info" Type="submit" Content="Submit"></SfButton>
</EditForm>
@code{
public class Countries
{
public string Name { get; set; }
public int? Code { get; set; }
[Required]
public int? dropVal { get; set; } = 2;
}
List<Countries> Country = new List<Countries>
{
new Countries() { Name = "Australia", Code = 1 },
new Countries() { Name = "Bermuda", Code = 2 },
new Countries() { Name = "Canada", Code = 3 }
};
public Countries model = new Countries();
}
|
|
Required validation |
Success validation |
|
|
|
When using a DropDownList with the DataAnnotation Required attribute, the border may not automatically turn red because the dropdown is already rendered with a selected default value or the validation CSS is not being applied correctly. To ensure proper validation, you should include an empty or placeholder option (such as “Select an option”) with an empty value so the Required attribute can trigger validation when nothing is chosen. Also make sure client-side validation is enabled and that the validation CSS classes (like input-validation-error) are correctly styled in your CSS. With the correct placeholder option and validation setup, the dropdown list will properly display a red border when the model state is invalid.
Hi Ali Jaan,
Thank you for your valuable suggestion we appreciate you pointing out a better way to handle this scenario. We have validated the details, and you can achieve the expected behavior by removing the initially assigned value for dropVal and updating the placeholder as required.
With this setup:
This ensures the dropdown integrates smoothly with the Required attribute and displays the proper validation feedback.
For your reference, we have also included a sample along with a GIF demonstration below to illustrate the behavior more clearly.
Gif: