【问题标题】:How to render an HTML attribute from a Razor view如何从 Razor 视图呈现 HTML 属性
【发布时间】:2010-12-30 06:52:17
【问题描述】:

我想对创建、编辑和详细信息视图使用相同的局部视图,以避免重复实体的字段集结构。然后,根据哪个视图呈现部分视图,我想在我的字段集周围的 div 中添加一个“只读”类,并使用 css 或 jQuery 处理在客户端上将实际输入字段设为只读,或者任何。如何从我的 Razor 视图中指定我需要将此类添加到“item-details”div 中?

<div class="item-details">
    <fieldset>
        <legend>Product Details</legend>
        @Html.HiddenFor(model => model.DetailItem.ProductId)
        <div class="editor-label">
            @Html.LabelFor(model => model.DetailItem.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DetailItem.Name)
            @Html.ValidationMessageFor(model => model.DetailItem.Name)
        </div>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
</div>

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 razor


    【解决方案1】:

    我通常会在模型上有一个变量来指示您的数据是否可编辑,并像这样使用它:

    <div class="item-details @(Model.IsReadOnly ? "read-only" : "")">
    

    但是,如果您的模型上没有它,您可以使用ViewBag。在您的父视图中:

    @{
        ViewBag.IsModelReadOnly = true;
    }
    

    在你的部分观点中:

    <div class="item-details @(ViewBag.IsModelReadOnly ? "read-only" : "")">
    

    您的只读视图的 html 输出将是

    <div class="item-details read-only">
    

    然后您可以通过 jQuery 访问 div 并执行您需要的操作:$(".read-only")...

    【讨论】:

      【解决方案2】:

      为什么不直接使用

      @Html.DisplayFor(model => model.[whatEver Property you are trying to show])

      【讨论】:

        猜你喜欢
        • 2011-12-07
        • 2011-05-19
        • 2013-05-13
        • 2017-05-06
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多