ASP.NET Core MVC : @Html.DropDownList on change pass ViewBag as parameter

219 Views Asked by At

I am creating an ASP.NET Core MVC application. I have a @Html.DropDownList and in the on change function, I want to pass as parameter a ViewBag value

 @Html.DropDownList("PageSize", new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 }, { "30", 30 }, { "40", 40 }, { "50", 50 }, { "100", 100 } }, "Key", "Value", Convert.ToString(ViewBag.PageSize)), new { id = "SearchPageSize", style = "width: 100px;", @onchange = "AAA(ViewBag.CurrentSort)" })

The function AAA is never called, and I get this error

Uncaught ReferenceError: ViewBag is not defined at HTMLSelectElement.onchange

It does not like how I am passing the parameter ViewBag.CurrentSort

How can I solve this?

Thanks

1

There are 1 best solutions below

1
hijinxbassist On

The issue is the context, which is c#.
Since the property being set is from the c# side, no @ is required.
To get the quotes around the parameter, use string.Format.

onchange=string.Format("AAA('{0}')", ViewBag.CurrentSort)