Home > Enterprise >  ASP.Net Core Razor Page, selectedList not rendering
ASP.Net Core Razor Page, selectedList not rendering

Time:12-17

i am pretty new to asp.net core and just started developing a website with it. Recently, I encountered a problem. I have a page where there is a default dropdownlist for user to select the respective option(all the options are rendered from the selectedItem which I got from database)

However, when the user decides to add an extra dropdownlist(i use javascript to do it), the options are blank. Any suggestions?

Thank you.

function GetNewDropdown() {
            return '<hr /><div ><h4 >Please select your options</h4 > <div >'  
                ' <select  asp-items="@Model.Options"></div></div>';}

CodePudding user response:

Your dynamic dropdown is a tag helper. Tag helpers are server-side components. They only work when the page is initially rendered by the web server. They do not work in the browser.

What you can do is move the HTML from your JavaScript function to a partial page, and then use JavaScript to call a named page handler method that returns a PartialResult and load it into your page.

Partial:

@model List<SelectListItem>
<hr />
<div >
    <h4 >Please select your options</h4>
    <div >
        <select  asp-items="@Model"></select>
    </div>
</div>

Razor page:

<button id="add-dropdown">Add</button>
<div id="zone"></div>

@section scripts{
<script>
    $(function(){
        $('#add-dropdown').on('click', function(){
            $.get('?handler=options', function(response){
                $(response).appendTo('#zone');
            });
        });
    });
</script>
}

Named handler in PageModel:

public List<SelectListItem> Options { get; set; }
public PartialViewResult OnGetOptions()
{
    Options = new List<SelectListItem> { 
        new SelectListItem { Text = "a", Value = "1" }, 
        new SelectListItem { Text = "b", Value = "2" },
        new SelectListItem { Text = "c", Value = "3" },
    };
    return Partial("_DropdownPartial", Options);
}

You can read more about these things on my site:

  • Related