【问题标题】:Templates C#/MVC 4/Razor模板 C#/MVC 4/Razor
【发布时间】:2013-06-10 02:33:03
【问题描述】:

目标

使用 C# + MVC 4 + Razor 引擎创建共享 UI 模板。

问题

我不知道该怎么做。

详情

我有以下模板:

<li>
    <div class="introduction">
        <h3>{productName}</h3>
    </div>
    <div class="presentation">
        <img src="{productImage}" alt="" />
    </div>
    <div class="description">
        <p>Starting by</p>
        <h3>{minProductPrice}</h3>
        <p class="product-unity">/a <span class="product-measure" 
         data-measure-shortcut="{productMeasureShortname">{productMeasureName}
        </span></p>
    </div>
    <div class="controls">
        <button class="button green add" title="Add to comparsion list">+</button>
        <div class="tooltip-quantity">
            <p class="float-left">Quantity:</p>
            <form method="post" action="#">
                <input class="quantity float-left" name="product_quantity"
                maxlength="2" type="text" />
                <span class="float-left">/{productMeasureName}(s)</span>
                <button disabled class="button orange filled float-right">
                   Add
                </button>
            </form>
        </div>
        <button class="button light-blue filled compare float-right" title="This product is available in 6 stores">Compare</button>
    </div>
</li>

当我想调用它时,我会做这样的事情:

@Html.RenderMyTemplate("Product Name", "Product Image", "Min Product Price"...)

从逻辑上讲,参数将替换模板上的占位符。

有什么想法吗?

提前致谢!

【问题讨论】:

    标签: c# asp.net-mvc-4 razor


    【解决方案1】:

    你可以使用局部视图:

    @Html.Partial("MyView", Model)
    

    基本上,它使用模型 (Model) 作为常规剃须刀驱动模板呈现给定文件 (MyView)。

    在你的情况下(我使用string[] 作为Model,但你可以使用任何你想要的,例如IDictionary&lt;string, string&gt;):

    @Html.Partial("MyView", new[] { "Product Name", "Product Image", "Min Product Price" })
    

    在视图中:

    @inherits System.Web.Mvc.WebViewPage<string[]>
    <li>@Model[0]</li>
    

    更新(带字典)

    @Html.Partial("MyView", new Dictionary<string, object> { { "name", "Product1"}, { "price", 100 } })
    

    然后

    @inherits System.Web.Mvc.WebViewPage<Dictionary<string, object>>
    <li>@Model["name"]</li>
    

    【讨论】:

    • 我可以命名这个索引吗?我的意思是,有办法使用@Model['productName']?谢谢!
    • 你可以,但你必须使用Dictionary而不是string[],让我编辑我的答案
    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    相关资源
    最近更新 更多