Retained DropDownList selected value after PostBack in ASP.Net Core Razor Pages

sunkana
 
on Jan 13, 2022 10:22 PM
1298 Views

Hi,

This is my following code in index.cshtml

After I click submit, the textbox values are retained but selected value in dropdown is not. I need to capture the selected value and display after postback in .NET Core Razor page.

Can you please let me know how to achieve this?

Select Type
<select name="number" id="selAlpha">
    <option value=0>S1</option>
    <option value=1>A1</option>
    <option value=2>C1</option>
</select>
<br />
<br />
<div class="form-group">
    <label asp-for="@Model.SName" class="control-label"></label>
    <input asp-for="@Model.SName" class="form-control" id="txtServerName" />
    <span asp-validation-for="@Model.SName" class="text-danger"></span>
</div>
<br />
<div class="form-group">
    <input type="submit" id="btnSubmit" asp-page-handler="TestXYZ" />
    <image src="/images/Spinner-3.gif" id="imgLoad"/>
    <label style="font-size:x-small;background-color:white" id="lblMsg" > </label>
</div>

Code in my index.cshtml.cs

public void OnPostTestXYZ()
{
    if (ModelState.IsValid)
    {
        String SName = Request.Form[nameof(SName)];
        string sAlpha = Request.Form[("number")];
        Someclass dc = new Someclass();
        Result = dc.Test(SName, sAlpha);
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jan 14, 2022 05:57 AM

Hi sunkana,

Using the below article i have created the example.

ASP.Net Core: Populate Select List from Database

You need to set the selected value after PostBack. Refer the below sample.

Model

public class FruitModel
{
    [BindProperty]
    public int FruitId { get; set; }

    [BindProperty]
    public string FruitName { get; set; }
}

Namespaces

using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;

IndexModel

public class IndexModel : PageModel
{
    public SelectList Fruits { get; set; }

    public void OnGet()
    {
        this.Fruits = new SelectList(PopulateFruits(), "FruitId", "FruitName");
    }

    public void OnPostSubmit(FruitModel fruit)
    {
        this.Fruits = new SelectList(PopulateFruits(), "FruitId", "FruitName");
        string message = "Fruit Name: " + fruit.FruitName;
        message += "\\nFruit Id: " + fruit.FruitId;
        ViewData["Message"] = message;
        ViewData["Selected"] = fruit.FruitId;
    }

    private static List<FruitModel> PopulateFruits()
    {
        string constr = @"Data Source=.;Initial Catalog=Sample;uid=sa;pwd=pass@123;";
        List<FruitModel> fruits = new List<FruitModel>();
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "SELECT FruitName, FruitId FROM Fruits";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        fruits.Add(new FruitModel
                        {
                            FruitName = sdr["FruitName"].ToString(),
                            FruitId = Convert.ToInt32(sdr["FruitId"])
                        });
                    }
                }
                con.Close();
            }
        }

        return fruits;
    }
}

View

@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_DropDownList_ADO.Net.Pages.IndexModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post">
        <select id="ddlFruits" name="FruitId" asp-items="@Model.Fruits">
            <option value="0">Please select</option>
        </select>
        <input type="hidden" name="FruitName" />
        <input type="submit" value="Submit" asp-page-handler="Submit" />
    </form>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("change", "#ddlFruits", function () {
            $("input[name=FruitName]").val($(this).find("option:selected").text());
        });
    </script>
    @if (ViewData["Message"] != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("@ViewData["Message"]");
            });
        </script>
    }

    @if (ViewData["Selected"] != null)
    {
        <script type="text/javascript">
            $(function () {
                $("#ddlFruits").val("@ViewData["Selected"]");
            });
        </script>
    }
</body>
</html>

Screenshot