从ASP.NET MVC迁移至Core 2.0:Select标签Tag Helper的HTML属性设置问题
Hey there, let's walk through your migration question clearly. First off, the code snippet you proposed won't work as intended—here's why, plus the right approaches to replicate your original ASP.NET MVC behavior in Core 2.0.
Why Your Current Code Fails
Your original MVC code uses new { @class = cssClass } to pass a dynamically built CSS class string (combining select-arrow with Model.ControlCss) to the dropdown. But in your Core attempt:
- You're using a comma to separate class names (
form-control, cssClass)—CSS classes require spaces, not commas. cssClassis treated as a literal string here, not the variable you defined. The browser will try to apply a class named "cssClass" instead of using your dynamic value.
Correct Implementation Options
Option 1: Directly Inject the Variable into the Class Attribute
ASP.NET Core's Tag Helpers support Razor expressions directly in HTML attributes, so you can simply concatenate your fixed class and dynamic variable with a space:
@{ var cssClass = "select-arrow " + Model.ControlCss; }
<select asp-for="Value" asp-items="options" class="form-control @cssClass"></select>
Razor will parse @cssClass and replace it with your dynamic class string, resulting in the correct space-separated class list.
Option 2: Use an HTML Attributes Object (For Multiple Attributes)
If you need to set multiple HTML attributes (not just class), you can define an anonymous object like you did in MVC, then apply it to the select tag:
@{ var cssClass = "select-arrow " + Model.ControlCss; var htmlAttributes = new { @class = $"form-control {cssClass}", data_target = "#some-modal", // Example of another attribute required = "required" }; }
<select asp-for="Value" asp-items="options" @htmlAttributes></select>
This keeps all your attribute logic organized in one place, just like your original MVC approach.
Option 3: Conditional Class Addition (Bonus)
If you need to add classes based on conditions, you can use Razor's ternary expressions directly in the class attribute:
<select asp-for="Value" asp-items="options" class="form-control @cssClass @(Model.IsRequired ? "input-required" : "")"></select>
This lets you mix fixed classes, dynamic variables, and conditional classes seamlessly.
Final Notes
The key difference from MVC's Html.DropDownListFor is that Core's Tag Helpers let you write more native-looking HTML while still leveraging Razor for dynamic values. Just remember to use @ to reference variables in attributes and separate CSS classes with spaces, not commas.
内容的提问来源于stack exchange,提问作者mnu-nasir

