GET參數是什麼呢?如果有觀察過網址的結構,可能會時常看到
https://xxx.xxx.xxx.xx/Web/ActivitiesListC001100.aspx?Pindex=2&Keyword=高雄市
看到問號之後的字串Pindex=2&Keyword=高雄市
這個其實是一個傳遞給伺服器後端程式的一個參數的方式
這種方式就是叫作用GET方法傳遞參數
而我們今天要來教的就是,如果客戶端用GET傳來的參數
我們在MVC這邊該怎麼樣去接收,其實在NET Core這邊很多事情都變得很簡單
我們先建一個News2Controller.cs
namespace Kcg.Controllers
{
public class News2Controller : Controller
{
private readonly KcgContext _context;
public News2Controller(KcgContext context)
{
_context = context;
}
public IActionResult Index()
{
var result = from a in _context.News
join b in _context.Department on a.DepartmentId equals b.DepartmentId
join c in _context.Employee on a.UpdateEmployeeId equals c.EmployeeId
select new NewsDto
{
Click = a.Click,
Enable = a.Enable,
EndDateTime = a.EndDateTime,
NewsId = a.NewsId,
StartDateTime = a.StartDateTime,
Title = a.Title,
UpdateDateTime = a.UpdateDateTime,
UpdateEmployeeName = c.Name,
DepartmentName = b.Name
};
return View(result.ToList());
}
}
}
在建立一個對應的View,這邊都用原生寫法,先不用之前範例那樣Helper的寫法
@model IEnumerable<NewsDto>
@{
ViewData["Title"] = "Index2";
}
<h1>Index</h1>
<table class="table">
<thead>
<tr>
<th>
標題
</th>
<th>
部門
</th>
<th>
開始時間
</th>
<th>
點擊率
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@item.Title
</td>
<td>
@item.DepartmentName
</td>
<td>
@item.StartDateTime.ToString("yyyy-MM-dd")
</td>
<td>
@item.Click
</td>
</tr>
}
</tbody>
</table>
此時畫面應該有出現列表

接著我們加入一個搜尋標題的按鈕,這邊也先用原生的寫法,之後會教Razor的特殊寫法
<form action="/News2" method="get">
<input type="text" name="keyword" placeholder="請輸入標題" />
<button type="submit">搜尋</button>
</form>
當上方Form按下搜尋時,會使用get方法送出一個keyword欄位的參數,我們可以試試看

可以看到網址變成這樣了https://localhost:7207/News2?keyword=高雄
那在我們後端程式那裡怎麼拿到keyword中"高雄"的參數呢,很簡單就像下面這樣
public IActionResult Index(string keyword)
在括弧中宣告對應的名稱即可,真的是非常直覺又簡單
那接著我們要來簡單寫一下搜尋的功能
public IActionResult Index(string keyword)
{
var result = from a in _context.News
join b in _context.Department on a.DepartmentId equals b.DepartmentId
join c in _context.Employee on a.UpdateEmployeeId equals c.EmployeeId
select new NewsDto
{
Click = a.Click,
Enable = a.Enable,
EndDateTime = a.EndDateTime,
NewsId = a.NewsId,
StartDateTime = a.StartDateTime,
Title = a.Title,
UpdateDateTime = a.UpdateDateTime,
UpdateEmployeeName = c.Name,
DepartmentName = b.Name
};
if (!string.IsNullOrEmpty(keyword)) //這邊再進行關鍵字過濾
{
result = result.Where(x => x.Title.Contains(keyword));
}
return View(result.ToList());
}
如此列表就會在按下搜尋後,顯示過濾後的新聞

實務上,GET參數常見的是用在關鍵字搜尋和頁碼的功能,今天就先簡單的介紹關鍵字搜尋,之後有機會再來教實作列表頁碼的功能
範例檔:下載