如何在 MVC 中访问强类型数据

发布于 2024-12-26 08:08:12 字数 536 浏览 1 评论 0原文

我一直在寻找关于如何从 MVC 应用程序的视图访问强类型数据的良好解释(第一次接触 MVC),但似乎找不到它。这是我的控制器中的代码:

PersonDetailsModel personDetails = personProvider.GetPersonDetails(id);
return View("Person", personDetails);

我有一个名为 Person.aspx 的视图,它看起来像这样(几乎是空的):

<%@ Page Title="Title" Language="C#" Inherits="System.Web.Mvc.ViewPage<Models.PersonDetailsModel>" MasterPageFile="../MvcMasterPage.Master" %>

我本以为我可以在视图中执行类似 Model.property 或 Person.property 的操作来访问数据,但我不知道如何访问模型的实例。我确信这很容易,但我只是不明白。

I've been searching for a good explanation of how to access my strongly typed data from the View of my MVC app (first time touching MVC) and can't seem to find it. Here's the code in my controller:

PersonDetailsModel personDetails = personProvider.GetPersonDetails(id);
return View("Person", personDetails);

I have a view called Person.aspx which looks like this (pretty much empty):

<%@ Page Title="Title" Language="C#" Inherits="System.Web.Mvc.ViewPage<Models.PersonDetailsModel>" MasterPageFile="../MvcMasterPage.Master" %>

I would've thought I could just do something like Model.property or Person.property in the view to access the data, but I don't see how I can access the instance of my model. I'm sure it's easy, but I just don't see it.

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

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

发布评论

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

评论(1

不交电费瞎发啥光 2025-01-02 08:08:12

由于您有一个强类型视图,因此 Model 是您从控制器传递的模型的实例。因此,您可以直接访问其属性:

<%@ Page 
    Title="Title" 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<Models.PersonDetailsModel>"
    MasterPageFile="../MvcMasterPage.Master" 
%>

<div><%: Model.SomeProperty %></div>

Model 属性的类型为 Models.PersonDetailsModel

如果您使用 Razor 视图引擎,等效视图将如下所示:

@model Models.PersonDetailsModel
<div>@Model.SomeProperty</div>

Since you have a strongly typed view, Model is the instance of your model that you passed from the controller. So you could directly access its properties:

<%@ Page 
    Title="Title" 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<Models.PersonDetailsModel>"
    MasterPageFile="../MvcMasterPage.Master" 
%>

<div><%: Model.SomeProperty %></div>

The Model property will be of type Models.PersonDetailsModel.

And if you were using the Razor view engine the equivalent view would look like this:

@model Models.PersonDetailsModel
<div>@Model.SomeProperty</div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文