简体   繁体   English

从视图访问模型数据

[英]Accessing Models Data from the View

I have this model我有这个 model

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string LastName{ get; set; }
    public string Email { get; set; }
}

How to print the Name value in the View component?如何在 View 组件中打印 Name 值?

In your.cshtml file, add your Model by: @model <YourSolution_name>.Models.Student在 your.cshtml 文件中,通过以下方式添加 Model: @model <YourSolution_name>.Models.Student

And print it: <p>Model.Name</p>并打印出来: <p>Model.Name</p>

Specify model in view page and pass instance of model from controller method to view page.在查看页面中指定 model 并从 controller 方法传递 model 的实例到查看页面。 Following is an example of view page and controller.以下是查看页面和 controller 的示例。

Controller Example Controller 示例

using System.Web.Mvc;

namespace MVC_Net_Example.Controllers
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
    public class StudentController : Controller
    {   
        public ActionResult Index()
        {
            Student myStudent = new Student();
            myStudent.ID = 1;
            myStudent.Name = "Sylvester";
            myStudent.LastName = "Stallone";
            myStudent.Email = "sylvesterstallone@outlook.com";
            return View(myStudent);
        }
    }
}

Index View Page Example索引视图页面示例

@model MVC_Net_Example.Controllers.Student

@{
    ViewBag.Title = "Student Detail";
}

<table class="table">
    <tr>
        <td>
            @Html.DisplayFor(model => model.Name)
        </td>
        <td>
            @Html.DisplayFor(model => model.LastName)
        </td>
        <td>
            @Html.DisplayFor(model => model.Email)
        </td>
    </tr>
</table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM