Skip to main content
 首页 » 编程设计

c#之CS0411 : The type arguments for method 'System.Web.Mvc.Html.EditorExtensions.EditorFor>)' cannot be inferred from the usage

2024年02月20日30zengkefu

我有一个我创建的模型类;一个简单的 POCO 类:

public class ContactModel 
{ 
    [Required] 
    public string Name { get; set; } 
 
    [Required] 
    public string Email { get; set; } 
 
    [Required] 
    public string Message { get; set; } 
 
    [Required] 
    public string Work{ get; set; }         
} 

在一个 View 中,我想为这个模型调用和编辑:

<div class="contact-form"> 
    @Html.EditorFor(new Map.WebUI.Models.ContactModel()) 
</div> 

但是我得到了错误:

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0411: The type arguments for method 'System.Web.Mvc.Html.EditorExtensions.EditorFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Source Error:

考虑到 View 未强类型化到此对象类型,我如何为随机类调用编辑器?

请您参考如下方法:

在您的 View 中,您在顶部设置了 @model Map.WebUI.Models.ContactModel

那么就需要这样使用EditorFor了:

@Html.EditorFor(x => x.ContactModel()) 

参数是一个 Lamda 表达式。

编辑:

好吧,我不知道你不能改变它……所以……我认为你不能使用 EditorFor。 但是您可以做的是使用 PartialView 并使用:

@Html.Partial("YourContactView", new Map.WebUI.Models.ContactModel()) 

编辑 2

您还可以使用 @Html.Editor(string expression, ViewData data)...这样您就可以将要传递给 ViewData 对象中的编辑器的模型放置。