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:
- Select tag helper: https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper
- Partial pages: https://www.learnrazorpages.com/razor-pages/partial-pages
- Named handler methods: https://www.learnrazorpages.com/razor-pages/handler-methods#named-handler-methods