[MVC教學] 05. HTTP GET/POST

 · 1 min read

第一個 Web API

VS>檔案>新增>專案>Visual C#>Web>ASP.NET Web 應用程式>Web API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
 
namespace MvcHelloWebAPI.Controllers
{
    public class ValuesController : ApiController
    {
        // GET /api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
 
        // GET /api/values/5
        public string Get(int id)
        {
            return "value";
        }
 
        // POST /api/values
        public void Post(string value)
        {
        }
 
        // PUT /api/values/5
        public void Put(int id, string value)
        {
        }
 
        // DELETE /api/values/5
        public void Delete(int id)
        {
        }
    }
}

用 ActionResult 來 GET/POST

  • [HttpPost],是一個可選屬性,讓 MVC 知道我們是要用 Post 接收,這限制了調用,所以它只能通過 HTTP POST 請求,[HttpGet] 亦同
  • 不能在同一個路由同時用 [HttpGet] 和 [HttpPost]

HttpGet

[HttpGet] // httq://server/home/create, 新增資料用
public ActionResult Create()        
{
  //預設會對映到/Views/Home/Create.cshtml
  return View();
}

HttpPost

[HttpPost] // httq://server/home/create 送出表單時          
public ActionResult Create(PlayerModel player)
{
  //前方送來的資料會自動對應到 Player 上
  if (ModelState.IsValid) player.Save();
  //轉到httq://server/home/index
  return RedirectToAction("Index");
}
  • Post Form
[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);
}
  • Post string
[HttpPost]
public ActionResult PostData(string Value1, string Value2)
{
  ViewData["Result"] = Convert.ToInt32(Value1) + Convert.ToInt32(Value2);
  return View();
}
  • DB 操作
[HttpPost]
public ActionResult Create(Models.Daily postback)  // --Create POST--
{
  using (Models.MymoneyEntities db = new Models.MymoneyEntities())
  {
    db.Mymoney.Add(postback);  //將回傳資料postback,加入至Mymoney DB
    TempData["ResultMessage"] = String.Format("紀錄[{0}]成功建立", postback.Item);  //設定成功訊息
    db.SaveChanges();  //儲存資料
   }
   return RedirectToAction("Index");
}

ref

  • https://blog.darkthread.net/blog/asp-net-mvc3-intro-4/
  • https://ithelp.ithome.com.tw/articles/10192537
  • https://dotblogs.com.tw/regionbbs/2012/01/09/mvc_and_http_post