ViewBag
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="<https://learn.microsoft.com/aspnet/core>">building Web apps with ASP.NET Core</a>.</p>
</div>
<input type="text" value="@ViewBag.A1" />
<hr />
<input type="text" value="@ViewBag.A2" />
<hr />
<p>@ViewBag.A3</p>
@{
int number = 7;
string character = "皮卡丘for";
}
<ul>
@for (int i = 0; i < number; i++)
{
<li>@character</li>
}
</ul>
@{
var data = new List<string> { "7", "皮卡丘Foreach" };
}
<ul>
@foreach (var item in data)
{
<li>@item</li>
}
</ul>
<ul id="output"></ul>
<script>
let number = 7;
let character = "皮卡丘JS的FOR";
let output = document.getElementById("output");
// 使用 for 迴圈來顯示數字和字串
for (let i = 0; i < number; i++) {
let li = document.createElement("li");
li.textContent = character;
output.appendChild(li);
}
</script>
<h3>This is a test</h3>
using Microsoft.AspNetCore.Mvc;
namespace ASP20241018_2.Controllers
{
public class TestDataController : Controller
{
public IActionResult Index()
{
Console.WriteLine("TestDataController: Index method is called.");
ViewBag.A1 = 7;
ViewBag.A2 = "皮卡丘";
ViewBag.A3 = "皮卡丘-2";
return View();
}
}
}
Controller 與 View 的對應關係: 在 ASP.NET MVC 中,Controller 和 View 是根據約定來匹配的。當使用某個 Controller 時,ASP.NET 會自動尋找對應的 View 檔案。
TestDataController
的 View 應該放在 Views/TestData/
資料夾下,Index.cshtml
則對應 Controller 的 Index()
方法。路由設置:
在 Program.cs
或 Startup.cs
檔案中,可以通過路由來指定預設的 Controller 和 Action。例如:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=TestData}/{action=Index}/{id?}");
});
動態資料顯示:
可以在 Controller 中使用 ViewBag
或 ViewData
傳遞資料到 View。使用 Razor 語法在 cshtml
檔案中顯示資料:
// Controller 中
ViewBag.Character = "皮卡丘";
// View 中
<p>@ViewBag.Character</p>
HTML 中的 Razor 語法錯誤修正: 在 HTML 中使用 Razor 語法時,記得引號要正確閉合。例如:
<input type="text" value="@ViewBag.A1" />
<input type="text" value="@ViewBag.A2" />
用 for
迴圈顯示字串多次:
使用 JavaScript 的 for
迴圈來執行多次操作:
let character = "皮卡丘";
let output = document.getElementById("output");
for (let i = 0; i < 7; i++) {
let li = document.createElement("li");
li.textContent = character;
output.appendChild(li);
}
使用 forEach
遍歷陣列:
如果要遍歷一個陣列,可以使用 forEach
:
let data = [7, "皮卡丘"];
data.forEach(item => {
let li = document.createElement("li");
li.textContent = item;
output.appendChild(li);
});