简体   繁体   中英

How do I populate dropdownlist inside Razor pages Not MVC

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;
    }

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>

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