getting both Text and value of a drop down list

Anjali Agarwal 1,221 Reputation points
2023-11-16T23:08:54.4166667+00:00

I have the following Model:

using System.ComponentModel.DataAnnotations;
namespace EmployeeRecognition.Models
{
    public class Sections
    {
        [Key]
        public int SectionId { get; set; }
        public string SectionName { get; set; }
    }
}

This is how I am binding my drop down list in Razor view:

 <select asp-for="SectionId" class="form-control" asp-items="ViewBag.sections" required>
                            <option value="">--Select Section Name--</option>
    </select>

My controller has the following code:

     public async Task<IActionResult> Index()
        {
            List<Sections> Sections = new List<Sections>();
            Sections = await _lookupData.GetSectionNames();
            ViewData["sections"] = new SelectList(Sections, "SectionId", "SectionName");
            return View();
        }

when I select some value from the drop down list and on postback come to the controller, I only get the SectionId. Is it possible to get both SectionId and SectionName on HTTPPost.

any help will be highly appreciated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
3,758 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 48,476 Reputation points
    2023-11-16T23:36:47.94+00:00

    the browser only posts back the value. on postback your server code should recreate the list data, and lookup the description based on the value (if you have an error you will need to recreate the list anyway). you other option is to add a hidden field to store the description and have javascript update the hidden field when the select value changes.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful