Search code examples
c#asp.net-corerazortag-helpersasp.net-core-tag-helpers

Get SelectedItem Value while Dropdownlist Selected Index Change Razor MVC


I have one Tblproduct class which has List of GetTypes() to bind it into Dropdownlist below :

public partial class Tblproduct: AuditableEntity
{
    [DisplayName("Product Type")]
    public int? ProductTypeId { get; set; }


    public static List<SelectListItem> GetTypes()
    {
        List<SelectListItem> datas = new List<SelectListItem>();
    
        datas.Insert(0, new SelectListItem() { Value="",Text=""});
        datas.Insert(1, new SelectListItem() { Value= InventoryCatalogueID.ToString(), Text="Inventory Catalogue"});
        datas.Insert(1, new SelectListItem() { Value= ServiceCatalogueID.ToString(), Text="Service Catalogue"});
        datas.Insert(1, new SelectListItem() { Value= ServiceCatalogueID.ToString(), Text= "Sub-Assembly" });
        datas.Insert(1, new SelectListItem() { Value= ServiceCatalogueID.ToString(), Text= "Raw Material" });
        datas.Insert(1, new SelectListItem() { Value= ServiceCatalogueID.ToString(), Text= "Finish Good" });
        datas.Insert(1, new SelectListItem() { Value= ServiceCatalogueID.ToString(), Text= "Service Catalogue" });
    
        return datas;
    }
}

And I have one ViewModel :

public ProductVM(Tblproduct _model = null, bool isreadonly = false):base(_model, isreadonly,"ControllerName")
{
    types = Tblproduct.GetTypes();
}
        
public List<SelectListItem> types { get; set; }

And I also have succeeded to bind the list of Tblproduct GetTypes into a dropdown in the View :

<select2 asp-for="model.ProductTypeId" asp-items="@Model.types"/>

And what I am struggling now is, I need to add some input based on selected types. Do I need to use auto-post-back Helper to get selected value?

But if I use auto-post-back the dropdown will always select the first value…

Here is my imagination:

@if(Model.types = 'Finish Good'){
    //do something to add new input or select
}

But how to get the Dropdownlist SelectedIndex or SelectedText change ?


Solution

  • How to get the Dropdownlist SelectedIndex or SelectedText change ?

    It seems, you are trying to extract submitted dropdown value from your razor page while you change dropdown value.

    It can be achievable through onchnage event both using javascript or without javascript. I am showing you with razor page because javascript one is simple so you can do it by yourself.

    Let's have a look in practice how we can achieve that.

    First of all, we need an onchnage event which would be executed while any dropdown change event taken place.

    Further more, by that submitted value, you would filter the the list and retrieve your expected value.

    Let's, have a look at the code snippet:

    Razor cshtml.cs:

    public class OnDropdownValueChangeModel : PageModel
        {
            public static List<SelectListItem> GetAll()
            {
                return new List<SelectListItem>
                {
                    new SelectListItem() { Value = "0",  Text = "Please Select Value" },
                    new SelectListItem() { Value = "1", Text = "Inventory Catalogue" },
                    new SelectListItem() { Value = "2", Text = "Service Catalogue" },
                    new SelectListItem() { Value = "3", Text = "Sub-Assembly" },
                    new SelectListItem() { Value = "4", Text = "Raw Material" },
                    new SelectListItem() { Value = "5", Text = "Finish Good" },
                    new SelectListItem() { Value = "6", Text = "Service Catalogue" }
                };
            }
            public List<SelectListItem> selectListItems = new List<SelectListItem>();
            public string? ProductTypeId { get; set; }
            public string? SelectedValue { get; set; }
    
            public void OnGet()
            {
                selectListItems = GetAll();
            }
            public void OnPostMyMethod()
            {
                var dropdownChangedValue = Request.Form["ProductTypeId"].ToString();
                selectListItems = GetAll();
                var searchSelectedValueFromDropdownList = selectListItems.Where(item => item.Value == dropdownChangedValue).First().Text;
                SelectedValue = searchSelectedValueFromDropdownList;
            }
        }
    

    Razor cshtml:

    @page
    @model RazorPageDemoApp.Pages.OnDropdownValueChangeModel
    @{
    }
    <form method="post" asp-page-handler="MyMethod">
        <select class="form-control"
                asp-for="ProductTypeId"
                asp-items="Model.selectListItems"
                onchange="this.form.submit();">
        </select>
    </form>
    
    @if (@Model.SelectedValue != null)
    {
        <div class="alert alert-success">
           <label>Your seleted value were:</label> @Model.SelectedValue
        </div>
    }
    

    Output:

    enter image description here

    enter image description here

    Note: If you still need any further assistance you could refer to this sample.