先在 HomeController .cs 編寫
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace MVCTest.Controllers
{
public class HomeController : Controller
{
public class Student
{
public string id { get; set; }
public string name { get; set; }
public int score { get; set; }
public Student()
{
id = string.Empty;
name = string.Empty;
score = 0;
}
public Student(string _id, string _name, int _score)
{
id = _id;
name = _name;
score = _score;
}
}
public ActionResult Index()
{
DateTime date = DateTime.Now;
ViewBag.Date = date;
Student data = new Student("1", "小明", 50);
return View(data);
}
範例是用之前的來修改,該段已經不需使用
//public ActionResult Transcripts(string id, string name, int score)
//{
// Student data = new Student(id, name, score);
// return View(data);
//}
post有兩種寫法,第一種寫法使用model來傳遞資料
命名的名稱大小寫要一致,將利用model傳送和接收
public ActionResult Transcripts(Student model)
{
string id = model.id;
string name = model.name;
int score = model.score;
Student data = new Student(id, name, score);
return View(data);
第二種要告知使用post
須加上 [HttpPost]標籤 ,讓MVC知道我們是要用Post接收
用post["id"]接收id欄位的內容,接收的資料原本就是string,所以不用轉換格式,只有int的部分要轉換格式
[HttpPost]
public ActionResult Transcripts(FormCollection post)
{
string id = post["id"];
string name = post["name"];
int score = Convert.ToInt32(post["score"]);
Student data = new Student(id, name, score);
return View(data);
}
}
}
編輯 Home/Index.cshtml,和上一個範例一樣沒更動
@{
ViewBag.Title = "Home Page";
Layout = null;
var date = ViewBag.Date;
var student = ViewBag.Student;
var list = ViewBag.List;
}
@model MVCTest.Models.Student
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<form style="margin-left:10px;" method="get" action="/Home/Transcripts">
<div class="form-group">
<label for="exampleInputEmail1">學號</label>
<input type="text" class="form-control" id="id" name="id" aria-describedby="emailHelp" placeholder="Enter email" value="@Model.id">
<small id="emailHelp" class="form-text text-muted">請輸入數字</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">姓名</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Password" value="@Model.name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">分數</label>
<input type="text" class="form-control" id="score" name="score" aria-describedby="emailHelp" placeholder="Enter email" value="@Model.score">
</div>
<button type="submit" class="btn btn-primary">確定</button>
</form>