简体   繁体   中英

ASP.Net Core Razor Page, selectedList not rendering

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 class="card-body"><h4 class="card-title text-primary">Please select your options</h4 > <div class="row">' +
                ' <select class="form-control" asp-items="@Model.Options"></div></div>';}

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 class="card-body">
    <h4 class="card-title text-primary">Please select your options</h4>
    <div class="row">
        <select class="form-control" 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM