You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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#’s new { ... } to define anonymous types.
  • Since class is 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).htmlAttributes or use Option 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:07:41