0

How do I populate dropdownlist inside Razor pages Not MVC because I have the code working fine in .Net core MVC but not working in .Net core Razor Page How do I display the list in dropdown with asp-items="????????" i mean

How do I display from here

public IActionResult Droplist()
   {
        List<ListMode> _Define = PopulateList();
        return View(new SelectList(_Define, "PredefineID", "Predefine"));
    }

return View(……); in above code is not working in Razor page

In side my Razor page I have this.

@Page
@model…
<form method="post">
<select id="ddlDList" name="PredefineID" asp-items="????????">
<option value="0">Please select</option>
</select>
</form>
                                

Other part of the code Database: dbo.DropListTBL

PredefineID Predefine
1 Class
2 Subject
3 Option
4 Status

Model Class:

public class ListMode
{
    public int PredefineID { get; set; }
    public string Predefine { get; set; }
}

Also:

private static List<ListMode> PopulateList()
    {
        string constr = @"Data Source =.; initial Catalog = DBname; Integrated Security = True";
        List<ListMode> List_Mode = new List<ListMode>();
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "SELECT PredefineID, Predefine FROM dbo.DropListTBL";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        List_Mode.Add(new ListMode
                        {
                            Predefine = sdr["Predefine"].ToString(),
                            PredefineID = Convert.ToInt32(sdr["PredefineID"])
                        });
                    }
                }
                con.Close();
            }
        }

        return List_Mode;
    }

1 Answer 1

0

Here is a demo about populating dropdownlist inside Razor pages:

cshtml.cs:

    [BindProperty]
            public SelectList ListModes { get; set; }
            public IActionResult OnGet()
            {
                List<ListMode> _Define =PopulateList();
                ListModes = new SelectList(_Define, "PredefineID", "Predefine");
                return Page();
            }

cshtml:

<select id="ddlDList" name="PredefineID" asp-items="@Model.ListModes">
    <option value="0">Please select</option>
</select>
Sign up to request clarification or add additional context in comments.

1 Comment

I just tried this out, with a little adjustment on my code its work fine, thank you for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.