CKneeland
CKneeland

Reputation: 119

How do I return a value from a DropDownList in Razor Pages?

I have a web app that allows me to pull names from my Customer table inside my database and print them out in a drop-down menu. I can then select the name in the list, but I don't know how to actually implement returning that name so that I can plug it in elsewhere on the website.

In the CustomerPage.cshtml, I have a line that displays and populates the DropDownList:

@page
@model CDInsightsWeb.Pages.Customer.CustomerPageModel
@{
    ViewData["Title"] = "CustomerPage";
}

<h1>Select A Customer</h1>
<div class="text-center">
    <hr />
    @Html.DropDownList("name", new SelectList(Model.DisplayData, "customer_id", "name"), "Select Name")
</div>
<div>
    <a asp-page="/Customer/CreateCustomer">Create a Customer</a>
</div>

This is the code I have for my CustomerPage.cshtml.cs class:

namespace CDInsightsWeb.Pages.Customer
{
    public class CustomerPageModel : PageModel
    {
        private readonly ConnectionStringClass _db;

        public CustomerPageModel(ConnectionStringClass db)
        {
            _db = db;
        }

        public List<Model.Customer> DisplayData { get; set; }

        public async Task OnGet()
        {
            DisplayData = await _db.Customer.ToListAsync();
        }
        public async Task OnPost()
        {
            return RedirectToPage("/Assessment/AssessmentPage", new { Customer.name });
        }
    }
}

How might I return the value I select from this list?

Upvotes: 0

Views: 4196

Answers (2)

Always_a_learner
Always_a_learner

Reputation: 1304

Change below code according to your need:

Code behind:

    [BindProperty]
    public List<Customer> DisplayData { get; set; }

    public IActionResult OnGet()
    {
        DisplayData = new List<Customer>();
        DisplayData.Add(new Customer { customer_id = "101", name = "Arun" });
        DisplayData.Add(new Customer { customer_id = "102", name = "Sonu" });
        return Page();
    }

    public IActionResult OnPost(string name)
    {
        return RedirectToPage("/Assessment/AssessmentPage", new { name });
    }

View :

<h1>Select A Customer</h1>
<form method="post">
    <div class="text-center">
        <hr />
        @Html.DropDownList("name", new SelectList(Model.DisplayData, "name", "name"), "Select Name")
    </div>
    <div>
       <input value="submit" type="submit"/>
    </div>
</form>

Output :

enter image description here

Upvotes: 2

Melody Magdy
Melody Magdy

Reputation: 168

In the view; put the dropdown inside form tag, add input of type submit

In the code behind; add inside the action input parameter ex. (string name)

Upvotes: 0

Related Questions