【问题标题】:MVC 4 what's the difference between model and ModelMVC 4 模型和模型有什么区别
【发布时间】:2015-05-02 05:11:02
【问题描述】:

我已经快两年没有用 C# 编码了,所以我的知识已经丢失了。 我在一个项目中工作,我发现我不能使用模型在视图中做一些数据绑定的事情。在 Mvc 4+ 中,它是否将 @model [type] 更改为 WebPage.Model?我只熟悉Mvc3-。如果给出示例项目,我将不胜感激。

【问题讨论】:

  • 你的意思是在视图中使用(和 Razor 代码)?
  • 是的,在 mvc4+ 中,删除 @model?
  • 不要删除@model yourClass。这定义了视图中使用的模型,然后Model 用于访问其属性的值 - 例如<div>@Model.someProperty</div>,或在 html 助手中,例如@Html.DisplayFor(m => m.someProperty)

标签: asp.net-mvc-4 model-view-controller


【解决方案1】:

@model 用于在视图页面中“导入”模型,而@Model 表示导入的模型,您可以在其中检索其属性。

请看下面的例子:

@model MeuExemploMVC.Models.CarrinhoComprasViewModel

@{
    ViewBag.Title = "Purchase Cart";
}

<h2>@Model.Mensagem
</h2>
<fieldset>
    <legend>Purchase Cart</legend>

    <table>
        <caption>Products</caption>
        <thead>
        <tr>
            <th>Product</th>
            <th>Price</th>
        </tr>
        </thead>
        <tbody>
        @foreach (var product in Model.Products) {
            <tr>
                <td>@product.Name</td>
                <td>@product.Price</td>
            </tr>
        }
        </tbody>
        <tfoot>
            <tr>
                <td><strong>Total</strong></td>
                <td>@Model.TotalPrice</td>
            </tr>
        </tfoot>
    </table>

</fieldset>

在这里您看到@model 只是将模型对象导入页面,而@Model 您从检索到的模型中获得实际值。

Here 是来自 CodeProject 的教程,它说明了这种差异。请注意,此处提供了示例代码。

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2013-05-27
    • 1970-01-01
    • 2012-02-03
    相关资源
    最近更新 更多