我們繼續沿用了之前的畫面
這次改用Post傳送資料到同樣的頁面,在index.cshtml只要將Get改成Post
@{
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="post" 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>
而後端HomeController.cs接收的部分多了一個Post的接收項目
using MVCTest.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
DateTime date = DateTime.Now;
ViewBag.Date = date;
Student data = new Student("1", "小明", 80);
return View(data);
}
public ActionResult Transcripts(string id, string name, int score)
{
Student data = new Student(id, name, score);
return View(data);
}
[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);
}
}
}
有加[HttpPost]標籤的是Post的方法,讓MVC知道我們是要用Post接收,可以跟上面的Get方法來比較,我們用FormCollection post來接收資料,然後用post["id"]接收id欄位的內容,接收的資料原本就是string,所以不用轉換格式,只有int的部分要轉換格式,後面就跟前一個範例一樣,在下面有提供畫面跟cshtml檔案
網頁畫面
以下是Transcripts.cshtml的部分:
@{
ViewBag.Title = "Transcripts";
Layout = null;
}
@model MVCTest.Models.Student
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<div class="form-group">
<label>學號: </label>
<label>@Model.id</label>
</div>
<div class="form-group">
<label>姓名: </label>
<label>@Model.name</label>
</div>
<div class="form-group">
<label>分數: </label>
<label>@Model.score</label>
</div>
p.s.
會不會覺得我很懶,
本來就是很懶啊...
--
小弟不才,
如果有謬誤或是要補充的,
都歡迎一起來討論!