山东网站建设,中国商铺网,长治做网站的公司,wordpress 代码缓存Index页
右键单击“视图”文件夹#xff0c;然后单击“添加”“新文件夹”#xff0c;并将文件夹命名为“HelloWorld”。
右键单击“Views/HelloWorld”文件夹#xff0c;然后单击“添加”“新项”。
在“添加新项 - MvcMovie”对话框中#xff1a;
在右上…Index页
右键单击“视图”文件夹然后单击“添加”“新文件夹”并将文件夹命名为“HelloWorld”。
右键单击“Views/HelloWorld”文件夹然后单击“添加”“新项”。
在“添加新项 - MvcMovie”对话框中
在右上角的搜索框中输入“视图”选择“Razor 视图 - 空”保持“名称”框的值Index.cshtml。选择“添加” 将 Views/HelloWorld/Index.cshtmlRazor 视图文件的内容替换为以下内容
{ViewData[Title] Index;
}h2Index/h2pHello 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 方法以将 Message 和 NumTimes 值添加到 ViewData 字典。
ViewData 字典是动态对象这意味着任何类型都可以使用。 在添加某些内容之前ViewData 对象没有已定义的属性。 MVC 模型绑定系统自动将命名参数 name 和 numTimes 从查询字符串映射到方法中的参数。 完整的 HelloWorldController
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 的内容替换为以下内容
{ViewData[Title] Welcome;
}h2Welcome/h2ulfor (int i 0; i (int)ViewData[NumTimes]!; i){liViewData[Message]/li}
/ul
保存更改并浏览到以下 URL
https://localhost:{PORT}/HelloWorld/Welcome?nameRicknumtimes4
数据取自 URL并传递给使用 MVC 模型绑定器的控制器。 控制器将数据打包到 ViewData 字典中并将该对象传递给视图。 然后视图将数据作为 HTML 呈现给浏览器。