ASP.NET MVC 从入门到放弃(Day22)-MVC新增资料介绍

接下来讲讲新增 部分...

Controller

public ActionResult Create()
{
 return View();
}

1.主画面View按下按钮导向Controller Create Action
https://ithelp.ithome.com.tw/upload/images/20210908/201400010VDnmGORWy.png

2.Create一个新个View 选Create范本
https://ithelp.ithome.com.tw/upload/images/20210908/20140001HXO2mKNHKG.png

类别 Model模板

public class Category
{

        [Display(Name = "类别种类")]
        public int CateType { get; set; }

        [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 bool IsCategoryidExist(string categoryid)
        {

            string connectionString = Server=127.0.0.1;userid=root; password=11111111; database=test;


            using (var conn = new MySqlConnection(connectionString))
            {

                conn.Open();

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

                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                }
            }

        }

        public bool Post_Category(Category category,int type, string InputUserID)
        {
            
string connectionString = Server=127.0.0.1;userid=root; password=11111111; database=test;
            
var result = false;
            using (var conn = new MySqlConnection(connectionString))
            {
                conn.Open();

                using (var command = conn.CreateCommand())
                {
                    command.CommandText = "Insert Into Category (Category,Category_Name,ModifyDate,ModifyEID) VALUES(@Category,@Category_Name,Now(),@InputUser)";
                    command.Parameters.AddWithValue("@Category", category.CategoryID);
                    command.Parameters.AddWithValue("@Category_Name", category.CategoryName);
                    command.Parameters.AddWithValue("@InputUser", InputUserID);
                    command.ExecuteNonQuery();
                    result = true;
                }
            }
            return result;
        }
}

1.属性宣告类别模板
2.IsCategoryidExist判断该类别有无存在
3.Post_Category 写入类别资料

Create View

@model WebApplication1.Models.Category.Category

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout2.cshtml";
}

@using (Html.BeginForm("Create", "Category", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <h2>类别资料新增作业</h2>
        <hr />

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

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CategoryID, htmlAttributes: new { @class = "control-label col-md-1" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CategoryID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CategoryName, htmlAttributes: new { @class = "control-label col-md-1" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CategoryName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CategoryName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="存档" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("返回清单", "Index")
</div>

1.@using (Html.BeginForm) 表单送出Razor语法 分别为 Create(Action) Category(Controller) FormMethod.Post(送出方法)
[email protected]() 避免CSRF攻击 (会产生一组Token给Server去做比对) 送出的Controller 需加上 [ValidateAntiForgeryToken]
3.@class bootstrap 语法 (class C#是保留字 所以要引用Html5 需加@)
[email protected] 後续会讲...
5.需宣告类别对应模板 @model WebApplication1.Models.Category.Category
6.如果要上传档案 @using (Html.BeginForm("Create", "Category", FormMethod.Post, new { enctype = "multipart/form-data" })) 需要加上new { enctype = "multipart/form-data" }

新增表单送出 Controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Category postback)
        {
            try
            {
                if (this.ModelState.IsValid)
                {
                    if (!new Category().IsCategoryidExist(postback.CategoryID, Type))
                    {
                        ViewBag.ResultMessage = "类别编号已存在";
                        ViewBag.Type = Type;
                        return View(postback);
                    }
                    else
                    {
                        var result = new Category().Post_Category(postback, Type, (string)Session["UserID"]);
                        if (result)
                        {
                            TempData["ResultMessage"] = String.Format("类别[{0}]成功新增", postback.CategoryID);
                            return RedirectToAction("Index", "Category");
                        }
                        else
                        {
                            ViewBag.ResultMessage = "资料有误,请检查";
                            ViewBag.Type = Type;
                            return View(postback);
                        }
                    }

                }
                else
                {
                    ViewBag.ResultMessage = "资料有误,请检查";
                    ViewBag.Type = Type;
                    return View(postback);
                }
            }
            catch (Exception e)
            {
                ViewBag.ResultMessage = e.ToString();
                return View();
            }
        }
  1. [HttpPost] 为View @using (Html.BeginForm) 送出方法
  2. [ValidateAntiForgeryToken] 为View @Html.AntiForgeryToken() 对应的避免CSRF攻击 的判断
  3. 参数可放 Category postback 接收表单的资料
  4. 如果要接收档案参数可加上HttpPostedFileBase file

新增表单送出未对应Model作法 Controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(FormCollection myForm)
        {
            int categoryID = myForm["CategoryID"];
            String categoryName = myForm.Form["CategoryName"]; 
        }

注解:一般正常还是建议走Model Binder 方式撰写 这边只是提供一个作法
注解2:.Net6版本 请在FormCollection 前面加入I (IFormCollection)

细节部分请参照
The Will Will Web FormCollection 说明


<<:  [Day12] Storybook - Writing Docs

>>:  Day15 简易资料库RealmSwift小实作2

19.MYSQL NOT指令

NOT与!的意思相同,它代表的意思是,运算结果为0时回传1,其他都回传1 WHERE NOT (AG...

Day 14 混合云备份

过去我们听闻过因为资料毁损、遗失不可朔原而造成的企业重大灾难,甚至有企业因此而关门,资料备份在现代...

D29 - 走!去浏览器自己刻表单选 pizza 口味

前言 自己设计 pizza 材料表单! 认识 html input 标签 input 可以用在表单输...

[Cmoney 菁英软件工程师战斗营] IOS APP 菜鸟开发笔记(2)

前言 从上周末开始到周三,除了学习老师教的观察者模式(Observer Pattern)和几种排序方...

WordPress 如何关闭 XML-RPC 服务,避免资安攻击风险

为了提升 WordPress 站台安全性,我安装了防火墙及防毒外挂 Wordfence,此外挂提供了...