接下来讲讲Model 部分...
简单来说Model负责与资料库沟通的相关逻辑,或者定义模板(.cs),或是使用Entity Framework自动产生资料库对应的模板(类别(.cs))後...交给Controoler去处理..
Category.cs 类别档
public class Category
{
public int CateType { get; set; }
public string CategoryID { get; set; }
public string CategoryName { get; set; }
public Category()//建构值
{
}
public static List<Category> Get_Gategory(int id)
{
List<Category> result = new List<Category>();
string connectionString = GlobalFunction.GlobalConnString;
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT Category, Category_Name FROM Category WHERE CateType = @CateType";
command.Parameters.AddWithValue("@CateType", id);
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;
}
}
}
}
}
}
上方public string CategoryName 就是类别档的模板, 接着再用Get_Gategory函式使用Ado 连线存在List 回传给Controoler
小帮手:如果要快速生成属性(property)
public int CateType { get; set; }
可以在类别档加入prop 按2次Tab键即可
补充说明:如果使用.Net6版本 属性(property) 预设要加入? (?代表允许Null)
public int? CateType { get; set; }
且显示画面Model要加入!
@Model!.CateType
CategoryController.cs 控制器
public ActionResult Index(string id){
var category = Category.Get_Category(id);
return View(category);
}
Controoler收到资料後再透过return View() 将List资料丢给显示画面
Index.cshtml 显示画面
@model IEnumerable<WebApplication1.Models.Category.Category>
<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 { Type = ViewBag.Type, categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-pencil" })
</td>
<td>
@Html.ActionLink("删除", "Delete", new { Type = ViewBag.Type, categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-trash", @onclick = "return Confirm_Form('"+ md.CategoryID + "')" })
</td>
<td>@md.CategoryID</td>
<td>@md.CategoryName</td>
</tr>
}
</table>
Model Class加入写法
Class1.cs 类别档
public class Class1
{
public string Test1 { get; set; }
}
Controller 传统写法
Models.Class1 myClass = new Models.Class1();
myClass.Test1 = "Yaowen";
Controller 中期写法
Models.Class1 myClass = new Models.Class1
{
myClass.Test1 = "Yaowen";
};
VS2022的简化写法
Models.Class1 myClass = new ()
{
myClass.Test1 = "Yaowen";
};
<<: Day 24 - 设定开发帐号 HBuilder X - DCloud 注册
>>: 【Day10】:库函数包装—对於底层暂存器的操纵(上)
此刻所发生的所有事,都是你之前选择的结果。 Everything that is happening...
在上一篇开始进到终端机的操作後,我们接着要来把一些东西真正让git来进行版本控制。 在这个章节,主要...
前言 在React中通常我们并不会直接操作到DOM元素。 但有些情况反而需要操作DOM元素,来使使用...
在很多情况下,有些错误是我们可以预知的,就比如前面计算两个数相加的代码,在有些情况下,我们可以预知到...
hi!昨天说完mapping大概的概念之後,今天就来实际做做看吧! 这次是参考这个连结的程序码进行...