昨天成功建立了 Controller 也得到了回传值,但它终究只是字串,所以今天要让他正式传入网页呈现给使用者,这时候就需要让 View 来帮忙显示排版了!
这篇可以搭配官方说明文件食用:Part 3, add a view to an ASP.NET Core MVC app
先将昨天的 Index()
动作改为 IActionResult
型别并回传 View
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineShopCMS.Controllers
{
public class HelloWorldController : Controller
{
public IActionResult Index()
{
return View();
}
public string Welcome(string Name)
{
return "This is the Welcome Action : Hello, " + Name + " !!";
}
}
}
接着右键新增检视,建立一个空的 View 取名为Index.cshtml
以下列内容取代Index.cshtml
的档案内容
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>This is our Default View !</p>
和昨天一样执行程序并访问/HelloWorld
,这次成功导向到View了
ViewData 和 ViewBag 都是可以从後端把数据传递到前端的方法,用法也很简单,适合在页面有需要显示後端资料的时候使用,生命周期只有一个页面,当前端把数值载入完後就会自动消失了
试着在 Index()
动作加入下面程序码
public IActionResult Index()
{
ViewData["mystring1"] = "I am ViewData !";
ViewBag.mystring2 = "I am ViewBag !";
return View();
}
并在视图Index.cshtml
呼叫 ViewData 和 ViewBag,跟後端写法差不多但要加上@
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>This is our Default View !</p>
<p>@ViewData["mystring1"]</p>
<p>@ViewBag.mystring2</p>
最後看看结果 执行後就可以发现内容在前端显示了
<<: [想试试看JavaScript ] 浏览器里的 Javascript
这一篇,我想再参考官网的攻略写一篇, 不过内容多增加了一些程序上的处理,以及过拟合(Overfitt...
我们先来用insertion sort algorithm来解题。 虽然他的效率也不高,但这是很好理...
计算属性(Computed) 无传入值 具回传值(return) 对来源属性进行操作-> 触发...
前言 今日的程序码 => GITHUB 这次要来介绍 Flutter 的 Cloud Mess...
今天开了配对单给大家做 side project,有兴趣可以来找找夥伴,前後端 / UIUX 皆可~...