2016年6月22日 星期三

[研究] ASP.NET MVC 5入門(七)瞭解 Edit Method 和 Edit View

[研究] ASP.NET MVC 5入門(七)瞭解 Edit Method 和 Edit View

2016-06-22

這篇是參考下面這篇的學習,不過工具從 Visual Studio 2013 改成 Visual Studio 2015 with Update 2 繁體中文版;網頁上有提到一篇新的改用 Visual Studio 2015,但是那篇要另外安裝 ASP.NET Core,而目前最新為 ASP.NET Code 1.0.0 RC2,並非正式版,所以暫時不想安裝和參考那篇。

內容不是完全翻譯,因為練習的心得,有增加、刪減圖片和文字。

Getting Started with ASP.NET MVC 5
http://www.asp.net/mvc/overview/getting-started/introduction/getting-started

[研究] ASP.NET MVC 5入門(一)開始
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5_21.html

[研究] ASP.NET MVC 5入門(二)增加控制器(Controller)
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5controller.html

[研究] ASP.NET MVC 5入門(三)增加檢視(View)
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5view.html

[研究] ASP.NET MVC 5入門(四)增加模型(Model)
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5model.html

[研究] ASP.NET MVC 5入門(五)建立 SQL Server LocalDB 的連線字串
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5-sql-server-localdb.html

[研究] ASP.NET MVC 5入門(六)從 Controller 存取 Model 的資料
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5-controller-model.html

7. Examining the Edit Methods and Edit View
http://www.asp.net/mvc/overview/getting-started/introduction/examining-the-edit-methods-and-edit-view

********************************************************************************
把 Models\Movie.cs 修改如下
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]   
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }

    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}



[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }



Edit 超連結是由 Views\Movies\index.cshtml 的 Html.ActionLink 產生
App_Start\RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}



MoivesController.cs 有2個 Edit action methods

2個 Edit action methods
</table>
// GET: Movies/Edit/5
public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

// POST: Movies/Edit/5
// 若要免於過量張貼攻擊,請啟用想要繫結的特定屬性,如需
// 詳細資訊,請參閱 http://go.microsoft.com/fwlink/?LinkId=317598。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

Views\Movies\Edit.cshtml 開頭部分

@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
 
    <div class="form-horizontal">
        <h4>Movie</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID)

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

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

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

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

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

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


@Html.AntiForgeryToken() 產生一個隱藏的表單,它和 Movies Controller 的 Edit 方法相匹配,請參考 Cross-site request forgery (XSRF or CSRF)

XSRF/CSRF Prevention in MVC.
http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages



處理 POST 要求


MoivesController.cs 的第2個 Edit action methods
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

ValidateAntiForgeryToken 會驗證  @Html.AntiForgeryToken() 產生了 XSRF token


要讓 jQuery 驗證支援非英語系國家,必須安裝 globalize.js,方法如下
( 官方網頁上的畫面和實測不同,可能是 Visual Studio 不同版本,安裝畫面不同)




Views\Movies\Edit.cshtml 最下方的內容
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

改成
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    @*<script src="~/Scripts/globalize/globalize.js"></script>
    <script src="~/Scripts/globalize/cultures/globalize.culture.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).js"></script>*@
    <script src="~/Scripts/globalize.0.1.3/globalize.js"></script>
    <script src="~/Scripts/globalize.0.1.3/cultures/globalize.culture.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).js"></script>
    <script>
    $.validator.methods.number = function (value, element) {
        return this.optional(element) ||
            !isNaN(Globalize.parseFloat(value));
    }
    $(document).ready(function () {
        Globalize.culture('@(System.Threading.Thread.CurrentThread.CurrentCulture.Name)');
    });
    </script>
    <script>
    jQuery.extend(jQuery.validator.methods, {
        range: function (value, element, param) {
            //Use the Globalization plugin to parse the value
            var val = Globalize.parseFloat(value);
            return this.optional(element) || (
                val >= param[0] && val <= param[1]);
        }
    });
    $.validator.methods.date = function (value, element) {
        return this.optional(element) ||
            Globalize.parseDate(value) ||
            Globalize.parseDate(value, "yyyy-MM-dd");
    }
    </script>
}

因為 globalize 安裝路徑和官方不同
原來下面的這段根據路徑做了修改
<script src="~/Scripts/globalize/globalize.js"></script>
<script src="~/Scripts/globalize/cultures/globalize.culture.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).js"></script>
成為
    <script src="~/Scripts/globalize.0.1.3/globalize.js"></script>
    <script src="~/Scripts/globalize.0.1.3/cultures/globalize.culture.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).js"></script>

或把 web.config 中強行設定為英語
 <system.web>
    <globalization culture ="en-US" />
    <!--elements removed for clarity-->
  </system.web>
(完)

[研究] ASP.NET MVC 5入門(一)開始
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5_21.html

[研究] ASP.NET MVC 5入門(二)增加控制器(Controller)

[研究] ASP.NET MVC 5入門(三)增加檢視(View)
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5view.html

[研究] ASP.NET MVC 5入門(四)增加模型(Model)
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5model.html

[研究] ASP.NET MVC 5入門(五)建立 SQL Server LocalDB 的連線字串
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5-sql-server-localdb.html

[研究] ASP.NET MVC 5入門(六)從 Controller 存取 Model 的資料
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5-controller-model.html

[研究] ASP.NET MVC 5入門(七)瞭解 Edit Method 和 Edit View
http://shaurong.blogspot.com/2016/06/aspnet-mvc-5-edit-method-edit-view.html


沒有留言:

張貼留言