错误:编译错误
描述:编译服务此请求所需的资源期间发生错误。请查看以下具体错误详细信息并适当修改您的源代码。
编译器错误消息:CS1928:“System.Web.Mvc.HtmlHelper”不包含“Label”的定义和最佳扩展方法重载“System.Web.Mvc.Html.LabelExtensions.Label(System.Web. Mvc.HtmlHelper, string, string)' 有一些无效参数
来源错误:
第 11 行:@Html.Label("Email", new { style = "width: 200px"})
我正在做的事情:由于我是初学者,因此将 CSS 和样式应用于 MVC 中的 RAZOR。
@using (Html.BeginForm("register","Home", FormMethod.Post, new {id="submitForm"}))
{
<div style="Width:200px">
<i>@Html.Label("Name:", new { style = "width:200px;" })</i>
@Html.TextBox("txtboxName")
</div>
<br />
<div style="Width:200px">
<i>@Html.Label("Email:")</i>
@Html.TextBox("txtboxEmail")
</div>
<br />
<div style="Width:200px">
<i>@Html.Label("Password:")</i>
@Html.Password("txtboxPassword")
</div>
<br />
<div>
<button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
</div>
}
最佳答案
Html.Label
的第一个参数实际上是一个字符串表达式。它本质上与没有强类型表达式的 LabelFor
相同。
这些表达式告诉 ASP.Net 在哪里查找元数据。但就您而言,您只想输出一个文字字符串。
因此,你可以简单地说:
<label style="width:200px;">Name:</label>
如果您确实想从属性元数据中派生值(这通常是个好主意),您可以构建一个如下所示的 View 模型:
// view model
public sealed class MyViewModel
{
[DisplayName( "An Email Address" )]
public string Email
{
get;
set;
}
}
// in your Razor view
@Html.LabelFor( o => o.Email, new { style = "width: 200px" } )
@Html.TextBoxFor( o => o.Email )
请注意,对于上述 View 模型,您现在可以使用 Label
方法。第一个参数对应于 View 模型中的属性名称。
@Html.Label( "Email", new { style = "width: 200px" } )
由于这依赖于字符串,因此它比前面的示例更脆弱,但它回答了您关于正确使用重载的原始问题。
出于好奇,我浏览了 MVC 源代码来了解如何处理标签表达式。 Label
的第一个字符串参数肯定是用作表达式(而不是文字),但如果无法导出表达式,框架会将其视为字符串。
换句话说,在某些情况下,您的代码实际上可以工作,但这是可能会改变的内部行为,不应依赖。
但是,您收到错误的事实可能表明代码中其他地方存在其他问题。
关于css - RAZOR 中的标签重载无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20852272/