ASP.NET Core MVC -- 将视图添加到 ASP.NET Core MVC 应用

Index页

右键单击"视图"文件夹,然后单击"添加">>"新文件夹",并将文件夹命名为"HelloWorld"。

右键单击"Views/HelloWorld"文件夹,然后单击"添加">"新项"。

在"添加新项 - MvcMovie"对话框中:

  • 在右上角的搜索框中,输入"视图"
  • 选择"Razor 视图 - 空"
  • 保持"名称"框的值:Index.cshtml
  • 选择"添加"

Views/HelloWorld/Index.cshtmlRazor 视图文件的内容替换为以下内容:

cs 复制代码
@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>Hello from our View Template!</p>

导航到 https://localhost:{PORT}/HelloWorld

  • HelloWorldController 中的 Index 方法运行 return View(); 语句,指定此方法应使用视图模板文件来呈现对浏览器的响应。

  • 由于未指定视图模板文件名称,因此 MVC 默认使用默认视图文件。 如果未指定视图文件名称,则返回默认视图。 默认视图与操作方法的名称相同,在本例中为 Index。 使用视图模板 /Views/HelloWorld/Index.cshtml

  • 下图显示了视图中硬编码的字符串"Hello from our View Template!":

将数据从控制器传递给视图

HelloWorldController.cs 中,更改 Welcome 方法以将 MessageNumTimes 值添加到 ViewData 字典。

ViewData 字典是动态对象,这意味着任何类型都可以使用。 在添加某些内容之前,ViewData 对象没有已定义的属性。 MVC 模型绑定系统自动将命名参数 namenumTimes 从查询字符串映射到方法中的参数。 完整的 HelloWorldController

cs 复制代码
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

namespace MvcMovie.Controllers;

public class HelloWorldController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    public IActionResult Welcome(string name, int numTimes = 1)
    {
        ViewData["Message"] = "Hello " + name;
        ViewData["NumTimes"] = numTimes;
        return View();
    }
}

ViewData 字典对象包含将传递给视图的数据。

创建一个名为 Views/HelloWorld/Welcome.cshtml 的 Welcome 视图模板。

Welcome.cshtml 视图模板中创建一个循环,显示"Hello"NumTimes。 将 Views/HelloWorld/Welcome.cshtml 的内容替换为以下内容:

cs 复制代码
@{
    ViewData["Title"] = "Welcome";
}

<h2>Welcome</h2>

<ul>
    @for (int i = 0; i < (int)ViewData["NumTimes"]!; i++)
    {
        <li>@ViewData["Message"]</li>
    }
</ul>

保存更改并浏览到以下 URL:

https://localhost:{PORT}/HelloWorld/Welcome?name=Rick&numtimes=4

数据取自 URL,并传递给使用 MVC 模型绑定器的控制器。 控制器将数据打包到 ViewData 字典中,并将该对象传递给视图。 然后,视图将数据作为 HTML 呈现给浏览器。

相关推荐
一点程序10 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
怪兽源码12 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
csdn_aspnet13 小时前
ASP.NET Core 中的依赖注入
后端·asp.net·di·.net core
昊坤说不出的梦14 小时前
【实战】监控上下文切换及其优化方案
java·后端
疯狂踩坑人14 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain
橘子师兄15 小时前
C++AI大模型接入SDK—ChatSDK封装
开发语言·c++·人工智能·后端
@ chen15 小时前
Spring事务 核心知识
java·后端·spring
一点技术17 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
RANCE_atttackkk17 小时前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程
好好研究19 小时前
Spring Boot - Thymeleaf模板引擎
java·spring boot·后端·thymeleaf