MVC 3:使用 EditorForModel 隐藏 ID 属性

发布于 2024-12-19 03:02:20 字数 391 浏览 4 评论 0原文

我的视图中有这一行:

@Html.EditorForModel()

这是我的 ViewModel:

public class CommentForm
{
    public int Id { get; set; }

    [DisplayName("Kommentar"), DataType(DataType.MultilineText)]
    public string Comment { get; set; }
}

问题是 Id 在表单中呈现为文本字段。实际上,我只想在表单操作中使用 Id 。是否有一个属性告诉编辑器不要渲染属性Id

I have this line in my View:

@Html.EditorForModel()

And this is my ViewModel:

public class CommentForm
{
    public int Id { get; set; }

    [DisplayName("Kommentar"), DataType(DataType.MultilineText)]
    public string Comment { get; set; }
}

The problem is that Id renders as a textfield in the form. Actually, I only want to use Id in the form action. Is there an attribute that tells the editor not to render the property Id?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冷默言语 2024-12-26 03:02:20

标准属性已将 ShowForDisplay 和 ShowForEdit 设置为 false

 [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] 


因此,您的自定义属性似乎有点矫枉过正。

Setting ShowForDisplay and ShowForEdit to false is already done by the standard

 [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] 

attribute.
Your custom attribute therefore seems like overkill.

余生再见 2024-12-26 03:02:20

一种可能性是将其呈现为隐藏字段:

[HiddenInput(DisplayValue = false)]
public int Id { get; set; }

另一种可能性是为您的 CommentForm 视图模型编写自定义编辑器模板,并在该模板中包含您想要的任何内容(~/Views/Shared/ EditorTemplates/CommentForm.cshtml):

@model CommentForm
<div>
    @Html.EditorFor(x => x.Comment)
</div>

One possibility is to render it as a hidden field:

[HiddenInput(DisplayValue = false)]
public int Id { get; set; }

Another possibility is to write a custom editor template for your CommentForm view model and inside this template include whatever you want (~/Views/Shared/EditorTemplates/CommentForm.cshtml):

@model CommentForm
<div>
    @Html.EditorFor(x => x.Comment)
</div>
辞取 2024-12-26 03:02:20

感谢您的贡献,但我不太喜欢它们。

我制作了自己的 PreventRenderingAttribute。

PreventRenderingAttribute.cs

[AttributeUsage(AttributeTargets.Property)]
public class PreventRenderingAttribute : Attribute, IMetadataAware
{
    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.ShowForDisplay = false;
        metadata.ShowForEdit = false;
    }
}

并在 CommentForm 中

[PreventRendering]
public int Id { get; set; }

Thanks for your contributions, but I didn't really like them.

I made my own PreventRenderingAttribute.

PreventRenderingAttribute.cs

[AttributeUsage(AttributeTargets.Property)]
public class PreventRenderingAttribute : Attribute, IMetadataAware
{
    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.ShowForDisplay = false;
        metadata.ShowForEdit = false;
    }
}

And in CommentForm

[PreventRendering]
public int Id { get; set; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文