C#转VB.NET:Razor视图匿名类型语法转换问题求助
C# to VB.NET Razor Anonymous Type Conversion & HtmlHelper Issue Fix
Hey there! I’ve dealt with this exact conversion headache before—let’s get this sorted out for you quickly.
1. Correct VB.NET Razor Syntax for Your Anonymous Type
First, the C# anonymous object syntax doesn’t translate directly to VB.NET. Here’s the proper conversion for your original code:
C# Original:
new { htmlAttributes = new { @class = "form-control" } }
VB.NET Razor Equivalent:
New With { .htmlAttributes = New With { .[class] = "form-control" } }
Key Differences Explained:
- VB uses
New With { ... }instead of C#’snew { ... }to define anonymous types. - Since
classis a reserved keyword in VB.NET, you need to wrap it in square brackets (.[class]) to avoid syntax errors. Alternatively, in VB 14+, you can use@as a prefix too:.@class = "form-control". - Critical: Always prefix anonymous type properties with a
.in VB Razor—this is a common gotcha that breaks syntax if missed.
2. Fixing the HtmlHelper additionalViewData Detection Issue
If your HtmlHelper isn’t picking up the htmlAttributes property, here are the most likely fixes:
- Exact Property Name Match: Ensure you’re using
htmlAttributes(lowercase first letter) exactly like in the C# code. VB is case-insensitive for most things, but .NET anonymous types preserve case—so if you accidentally wrote.HtmlAttributes(uppercase H), the HtmlHelper won’t recognize it. - Dynamic/Reflection Access: If you’re building a custom HtmlHelper method, make sure you’re accessing the property correctly. For VB, you can use
DirectCast(additionalViewData, Object).htmlAttributesor useOption Strict Off(not ideal, but works for quick testing) to access it dynamically. - Verify Razor Context: In VB Razor, make sure you’re not mixing code blocks incorrectly. For example, if you’re passing this as a parameter to an HtmlHelper method, ensure the entire anonymous type is within the method’s argument list (no extra line breaks that break the syntax).
Example Usage in VB Razor
Here’s how you’d use this converted type with a standard TextBoxFor helper:
@Html.TextBoxFor(Function(m) m.Username, New With { .htmlAttributes = New With { .[class] = "form-control" } })
内容的提问来源于stack exchange,提问作者P_R
相关产品推荐
相关产品推荐

