如何在 MVC 框架中创建类和调用方法的对象



请帮助我使用下面的简单模型类学习 asp.net MVC 概念。在哪里创建一个 Student 对象以及如何使用构造函数传递值并最终调用 StudentMessage(( 方法并在视图 (index.cshtml( 中显示结果。我一直在尝试在学生控制器类中创建一个 Student 对象,但它不起作用。请不要使用列表集合。我是 C# 的初学者。

namespace MyMVCApplication.Models
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public Student(int studentID, string studentName, int age)
{
this.StudentId = studentID;
this.StudentName = studentName;
this.Age = age;
}
public string StudentMessage()
{
string message = "Student ID: " + this.StudentId + "| Student Name: " + this.StudentId + "| Age: " + this.Age;
return message;
}
}  
}
namespace MyMVCApplication.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{            
return View();
}      
}
}

View - Index.cshtml

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>

如果要将学生模型传递给视图,请执行以下操作:

将模型粘贴到视图中

public ActionResult Index()
{            
Student modelStudent = new Student(studentID, studentName, age);
return View(modelStudent);
}

现在,您需要在视图索引中接收模型,将以下代码添加到index.cshtml中:

@model MyMVCApplication.Models.Student

现在,您可以使用如下命令在视图中访问模型属性(无需调用方法...

Student ID: @Model.StudentId | Student Name: @Model.StudentId | Age: @Model.Age

最新更新