iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
自我挑戰組

C# 學習之旅系列 第 21

ASP.NET MVC 從入門到放棄(Day21)-MVC查詢資料介紹

接下來講講查詢 部分...

Controller

public ActionResult Index(string id)
{
      
   String SearchString = id;
   try
   {
       if (!String.IsNullOrEmpty(SearchString))
       {
          var category = = Category.Get_Category(SearchString, type);
          return View(category);
       }
       else
       {
          var result =  Category.Get_Gategory(type);
          return View(result);
        }
    }
    catch (Exception e)
    {
       ViewBag.ResultMessage = e.ToString();
       return View();
    }
}

1.Create一個新個View 選List範本
https://ithelp.ithome.com.tw/upload/images/20210908/20140001xZ4Aw9qTPI.png

類別 Model模板

public class Category
{

        [Required]
        [Display(Name = "類別編號")]
        [StringLength(4, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 1)]
        public string CategoryID { get; set; }

        [Display(Name = "類別名稱")]
        [StringLength(20, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 1)]
        public string CategoryName { get; set; }

        public Category()
        {

        }
        public static List<Category> Get_Category(string categoryID)
        {
            List<Category> result = new List<Category>();

            using (var conn = new MySqlConnection(GlobalFunction.GlobalConnString))
            {

                conn.Open();

                using (var command = conn.CreateCommand())
                {
                    command.CommandText = "SELECT Category, Category_Name FROM Category WHERE Category = @Category ";
                    command.Parameters.AddWithValue("@Category", categoryID);

                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {

                            while (reader.Read())
                            {
                                result.Add(new Category()
                                {
                                    CategoryID = (string)reader["Category"],
                                    CategoryName = (reader.IsDBNull(reader.GetOrdinal("Category_Name"))) ? "" : (string)reader["Category_Name"]
                                });
                            }
                            return result;
                        }
                        else
                        {
                            return result;
                        }
                    }
                }
            }
        }
}

1.屬性宣告類別模板
2.Get_Category 取得類別資料
3.回傳List清單類別資料

List View

@model IEnumerable<WebApplication1.Models.Category.Category>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout2.cshtml";
}


<h2>類別資料管理作業</h2>
<br />

@if (ViewBag.ResultMessage != null)//判斷如果有訊息,則顯示。
{
    <script type="text/javascript">
            var message = @Html.Raw(Json.Encode(ViewBag.ResultMessage));
            alert(message);
    </script>
}

<div class="container">
    <div class="row">
        @using (Html.BeginForm("Index", "Category"))
        {

            @Html.AntiForgeryToken()

            <div class="table-responsive">
                <div id="toolbar">
                    <form class="form-inline">
                        <div class="form-group">
                            <div class="input-group">
                                <div class="input-group-addon">類別編號</div>
                                <input type="text" class="form-control" name="id" id="searchTexts" placeholder="請輸入類別編號">
                                <div class="column">
                                    <button type="submit" class="btn btn-primary queryButton"> 搜尋</button>
                                    @Html.ActionLink("新增類別", "Create", new { @class = "btn btn-primary" })
                                 
                                </div>
                            </div>
                        </div>
                    </form>

                </div>
            </div>

        }

    </div>
</div>



<table class="table">
    <tr>
        <th width="70">
            操作
        </th>
        <th width="70">
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().CategoryID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().CategoryName)
        </th>
        <th>

        </th>
    </tr>
    @foreach (var md in this.Model)
    {
        <tr>
            <td>
                @Html.ActionLink("編輯", "Edit", new { categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-pencil" })
            </td>
            <td>

                @Html.ActionLink("刪除", "Delete", new { categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-trash" })
            </td>
            <td>@md.CategoryID</td>
            <td>@md.CategoryName</td>
        </tr>
    }
</table>

1.@model 是一個關鍵字保留字 (宣告類型) 指的是資料屬性
2.Controller傳來IEnumerable 資料是一個集合屬性
3.@using (Html.BeginForm) 表單送出Razor語法 分別為 Index(Action) Category(Controller) FormMethod.Get(預設為不填)
4.type="submit" 會搭配 Html.BeginForm 送到Controller那裏
5.@class bootstrap 語法


上一篇
ASP.NET MVC 從入門到放棄(Day20) -MVC模型(Model) Entity Framework
下一篇
ASP.NET MVC 從入門到放棄(Day22)-MVC新增資料介紹
系列文
C# 學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言