ASP.NET MVC 5 学习教程:Edit方法和Edit视图详解

原文 ASP.NET MVC 5 学习教程:Edit方法和Edit视图详解

起飞网 ASP.NET MVC 5 学习教程目录:

在本节中,我们继续研究生成的Edit方法和视图。但在研究之前,我们先将 release date 弄得好看一点。打开 Models\Movie.cs 文件,添加下面黄色背景的行:

代码清单1: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)]
        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; }
    }
}

我们将在下一节中介绍 DataAnnotations。Display 特性指定了显示的字段名(本例中“Release Date”替换了“ReleaseDate”)。DataType 特性指定了数据类型,在本例中它是日期类型,因此存储在该字段的时间信息将不会显示出来。

运行应用程序,在浏览器地址栏中追加/movies 来访问 Movies 控制器。将鼠标放在Edit 链接上面,查看它链接到的地址:

图1:查看Edit链接地址

image

Edit 链接是通过Html.ActionLink 方法生成的,在Views\Movies\Index.cshtml 视图中,代码如下:

代码清单2:Html.ActionLink 方法

@Html.ActionLink("Edit", "Edit", new { id=item.ID })

图2:Html.ActionLink 方法介绍

image

Html 对象是System.Web.Mvc.WebViewPage 基类中的一个属性,ActionLink 方法使动态生成 控制器中方法的 HTML 超链接更为简单。ActionLink 方法的第一个参数是要显示的链接文字(例如<a>Edit Me</a>);第二个参数是要调用的控制器方法(在这里是 Edit 方法);最后一个参数是生成路由数据用的匿名对象(在这里是id,值为1)。

在图1中显示的生成地址是http://localhost:2264/Movies/Edit/1 。默认的路由匹配 {controller}/{action}/{id} URL模式 。因此,ASP.NET 将请求地址http://localhost:2264/Movies/Edit/1 翻译为MoviesController 的Edit 方法,参数id为1。查看App_Start\RouteConfig.cs 文件中的代码:

代码清单3:默认路由规则

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

你还可以使用查询字符串传递参数,例如 http://localhost:xxxxx/Movies/Edit?ID=1 也可以将参数id为1的值传递给Movies控制器。

图3:通过查询字符串传递参数

image

打开Movies控制器,它包含了两个Edit 方法,代码如下:

代码清单4:两个Edit方法 - MoviesController.cs

//
// GET: /Movies/Edit/5
public ActionResult Edit(Int32 id)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

//
// POST: /Movies/Edit/5

[HttpPost

]
[ValidateAntiForgeryToken]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

注意第二个 Edit 方法,它被HttpPost特性修饰(代码中黄色背景标注),这个特性指定只有POST请求才能调用这个重载的Edit方法。我们可以为第一个Edit方 法添加HttpGet特性,但这不是必须的,因为它是默认值(我们将未标记的方法认定为HttpGet方法)。第二个Edit 方法还有一个 ValidateAntiForgeryToken 特性,这个特性用来阻止伪造的请求,它和视图(Views\Movies\Edit.cshtml)中的 @Html.AntiForgeryToken() 是成对出现的。

代码清单5:@Html.AntiForgeryToken() 用法

@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset class="form-horizontal">
        <legend>Movie</legend>

        @Html.HiddenFor(model => model.ID)

        <div class="control-group">
            @Html.LabelFor(model => model.Title, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title, null, new { @class = "help-inline" })
            </div>
        </div>

@Html.AntiForgeryToken() 生成一个表单防伪标记,必须与 MoviesController 中的 Edit 方法匹配。

HttpGet标记的Edit方法接收一个ID的参数,通过Entity Framework Find方法查找电影,并将找到的结果返回个Edit 视图。如果调用Edit方法的时候没有参数,ID参数的值将会是默认的0。如果未找到电影信息,控制器将返回一个HttpNotFound。当支架系统创 建Edit 视图的时候,它会检查Movie类,为它的每一个属性创建绘制<label><input> 元素的代码。下面的示例展示了Visual Studio 支架系统创建的Edit视图代码:

代码清单6:Edit 视图

@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset class="form-horizontal">
        <legend>Movie</legend>

        @Html.HiddenFor(model => model.ID)

        <div class="control-group">
            @Html.LabelFor(model => model.Title, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="control-group">
            @Html.LabelFor(model => model.ReleaseDate, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.ReleaseDate)
                @Html.ValidationMessageFor(model => model.ReleaseDate, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="control-group">
            @Html.LabelFor(model => model.Genre, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Genre)
                @Html.ValidationMessageFor(model => model.Genre, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="control-group">
            @Html.LabelFor(model => model.Price, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Price)
                @Html.ValidationMessageFor(model => model.Price, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="form-actions no-color">
            <input type="submit" value="Save" class="btn" />
        </div>
    </fieldset>
}

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

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

在视图文件顶部的语句 @model MvcMovie.Models.Movie 指明该视图需要一个 Movie 型的模型。 

支架生成的代码使用了很多精简HTML标记的帮助方法,Html.LabelFor 方法用来显示字段名( "Title", "ReleaseDate", "Genre", 和 "Price"),Html.EditorFor 方法生成一个HTML <input> 元素,Html.ValidationMessageFor 方法结合属性显示一些验证信息。

运行应用程序,导航到 /movies 地址,点击 Edit 链接,在浏览器中,查看页面源代码,form标签的HTML代码如下:

代码清单7:生成的form标签HTML代码

<form action="/Movies/Edit/1" method="post">
    <

input name="__RequestVerificationToken" type="hidden" value="vM6-yBtYJY5uRgKm3ivFw9gLMjauE9i2-Wi6Y--2Swm4-BlucfrG71zQV3n773tT9i8ytaG5WSanfBBd54qIhAKAkTJO_Z0UhRaGPDhMJ9M1" /> <fieldset class

="form-horizontal">
        <legend>Movie</legend>

        <input data-val="true" data-val-number="The field ID must be a number." data-val-required="ID 字段是必需的。" id="ID" name="ID" type="hidden" value="1" />

        <div class="control-group">
            <label class="control-label" for="Title">Title</label>
            <div class="controls">
                <input class="text-box single-line" id="Title" name="Title" type="text" value="中国合伙人" />
                <span class="field-validation-valid help-inline" data-valmsg-for="Title" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="ReleaseDate">Release Date</label>
            <div class="controls">
                <input class="text-box single-line" data-val="true" data-val-date="The field Release Date must be a date." data-val-required="Release Date 字段是必需的。" id="ReleaseDate" name="ReleaseDate" type="date" value="2013/6/18" />
                <span class="field-validation-valid help-inline" data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="Genre">Genre</label>
            <div class="controls">
                <input class="text-box single-line" id="Genre" name="Genre" type="text" value="励志" />
                <span class="field-validation-valid help-inline" data-valmsg-for="Genre" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="Price">Price</label>
            <div class="controls">
                <input class="text-box single-line" data-val="true" data-val-number="The field Price must be a number." data-val-required="Price 字段是必需的。" id="Price" name="Price" type="text" value="70.00" />
                <span class="field-validation-valid help-inline" data-valmsg-for="Price" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="form-actions no-color">
            <input type="submit" value="Save" class="btn" />
        </div>
    </fieldset>
</form>

看一下这个form标签,它的action属性是/movies/edit/1,说明form将提交到这个地址,而它里面包含的<input>标签则对应每一个Movie类的字段。当点击“Save”按钮时,form中的数据将提交到服务器。第二行代码中,我使用高亮提示,这行代码是使用@Html.AntiForgeryToken() 生成的隐藏域,用来阻止伪造的请求。

处理POST请求

下面是接收POST请求的Edit方法:

代码清单8:Edit 方法

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

ASP.NET MVC model binder 使用提交的表单数据创建一个 Movie 对象,作为 movie 参数传递给 Edit 方法。ModelState.IsValid  验证 form 提交的数据是否能够用来修改(编辑或更新)Movie对象,如果验证通过,电影数据就会保存在 db.Movies 列表中(dbMovieDBContext 的实例),通过调用 db.SaveChanges 方法将修改后的电影数据保存在数据库中。在数据保存之后,RedirectToAction 将跳转到 Index 方法,用来显示电影列表,此时就能看到更新后的电影信息。

在用户输入过程中,一旦输入了未通过验证的值,客户端就会显示一个错误信息,这些功能是通过Javascript 完成的,如果你禁用了Javascript,客户端验证功能将会失效,但服务器会检查到不合法的数据,然后将包含错误信息的表单重新显示在客户端。在后面 的章节中我们将介绍更多验证的细节。

Edit.cshtml 视图中的 Html.ValidationMessageFor 方法会显示相应的错误信息。如下图:

图4:编辑Movie时的验证信息

image_thumb

所有处理Get请求的方法都有相似的模式:他们获取一个电影对象(在Index中是电影列表),然后传递给View。Create 方法传递一个空的电影数据给视图。使用HTTP GET 方法修改数据存在安全风险,也同样违背了HTTP最佳实践,并且 REST 模式中明确指出,GET 请求不应该改变应用程序的状态,换句话说,GET 操作应该是一个安全的操作,没有副作用,也不会修改你的持久化数据。

本地化验证

如果你是用英语,这部分可以跳过。作为汉语国家用户,我还是把这部分翻译一下吧。

对于非英语地区的用户来说,小数点使用逗号(","),还有非美语的日期格式,为了支持Jquery 验证,你必须包含 globalize.js 和特定的 cultures/globalize.cultures.js 文件,在Javascript中使用 Globalize.parseFloat。你可以通过NuGet获得 jQuery non-English validation (英语地区不要安装Globalize)。

From the Tools menu click Library Package Manager, and then click Manage NuGet Packages for Solution.

在菜单栏中单击“工具”>“库程序包管理器”>“管理解决方案的 NuGet程序包”。

图5:NuGet 菜单

image

在左侧单击“联机”,在查询框中输入“Globalize”:

图6:查询 Globalize 安装包

image

点击“安装”按钮,Scripts\jquery.globalize\globalize.js 文件将会添加到项目中,文件夹 Scripts\jquery.globalize\cultures\ 中包含了很多Javascript文件。

下面的代码显示了将文件 Views\Movies\Edit.cshtml 使用汉语区域所作的修改(原文作者使用法语作为演示):

代码清单9:script 代码 - Edit.cshtml

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/jquery.globalize/globalize.js"></script>
    <script src="~/Scripts/jquery.globalize/cultures/globalize.culture.zh-CN.js"></script>
    <script>
        $.validator.methods.number = function (value, element) {
            return this.optional(element) ||
                !isNaN(Globalize.parseFloat(value));
        }
        $(document).ready(function () {
            Globalize.culture('zh-CN');
        });
    </script>
    <script>
        jQuery.extend(jQuery.validator.methods, {
            range: function (value, element, param) {
                //Use the Globalization plugin to parse the value
                var val = $.global.parseFloat(value);
                return this.optional(element) || (
                    val >= param[0] && val <= param[1]);
            }
        });
    </script>
    <script>
        $.validator.methods.date = function (value, element) {
            return this.optional(element) ||
            !isDate(Globalize.parseDate(value));
        }
    </script>
}

为了避免在每个编辑视图都写上这么一大段代码,你可以将他们写在布局页。

在下一节中我们将为程序实现查找功能。

本文同时发布在起飞网,原文地址:http://www.qeefee.com/mvc/mvc-5-examining-the-edit-methods-and-edit-view

 

如果认为此文对您有帮助,别忘了支持一下哦!

作者: 齐飞
声明:本博客原创文字只代表本人工作中在某一时间内总结的观点或结论,与本人所在单位没有直接利益关系。非商业,未授权,贴子请以现状保留,转载时必须保留此段声明,且在文章页面明显位置给出原文连接。
posted on 2013-12-10 21:04 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/3468182.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
jQuery Widgets for PC, Mobile and Touch Devices jQuery Widgets for PC and Mobile What is jQWidgets? jQWidgets represents a framework based on jQuery for building web-based applications that run on PC, Touch and Mobile devices. jQWidgets includes more than 40 UI widgets. jQWidgets is not a modified version of the jQuery UI toolkit. All widgets are designed from ground-up and based on a powerful common core. The framework core provides fundamental capabilities like support for widget extensions and inheritance, widget settings, internal event handling and routing, property change notifications, device and browser compatibility detection and adjustments. Works across devices and browsers jQWidgets takes the JavaScript & HTML UI development to a new level. It is platform independent, cross-browser compatible and works on PC and mobile devices. Don抰 spend time testing on different devices and browsers. Use a reliable, CSS compliant JavaScript library based jQuery, HTML5 and CSS3.The product supports all major desktop and mobile web browsers - Internet Explorer 7.0+, Firefox 2.0+, Safari 3.0+, Opera 9.0+, Google Chrome, IE Mobile, Android, Opera Mini, Mobile Safari(IPhone, IPad). jQuery dependency and compatibility jQWidgets has a dependency on the jQuery library. jQWidgets is tested and compatible with all jQuery versions from jQuery 1.7.0 to jQuery 2.1.1. We are committed to supporting all new versions of jQuery and ensuring the highest level quality. At present, we highly recommend that you use jQuery 1.11.1. This version is stable, high quality, and works well with a large number of popular devices and browsers. It is ideal for enterprise web applications and Internet web sites where the visitors use a mix of mobile devices, PCs, new and older browsers. Important: jQuery team has decided that starting from jQuery version 1.9.0 the project will evolve in two parallel tracks. Versions 1.9.* will support older browsers while versions starting from 2.* will not. This means that if you are looking for the highest possible compatibility across the broadest set of devices and browsers, you should stick with versions earlier than 2.0.0 for some time. On the other hand, if you are using jQWidgets in a mobile application or building a solution where certain older browsers will not be required, feel free to use jQWidgets along with jQuery 2.0.0. It is important to emphasize that the pros and cons of maintaining compatibility with certain older browsers is always changing. If you want to make a good, well informed decision, we recommend you to check the recent browser usage statistics and analyze the browsers and devices used by your website抯 visitors. Optimized for Performance Small footprint, highly responsive, carefully optimized to deliver outstanding experience on a wide range of devices, operating systems and browsers. Theme Builder The Theme Builder is a powerful online tool that helps you to quickly create themes for the user interface of your application based on jQWidgets. Online Theme Builder Download and Installation Download jQWidgets Information about the distribution package The SDK files are located in the jqwidgets directory In general you need to use files from this directory only. Files list & description: Files required in all projects using the SDK jqxcore.js: Core jQWidgets framework Stylesheet files. Include at least one stylesheet Theme file and the images folder: styles/jqx.base.css: Stylesheet for the base Theme. The jqx.base.css file should be always included in your project. styles/jqx.arctic.css: Stylesheet for the Arctic Theme styles/jqx.web.css: Stylesheet for the Web Theme styles/jqx.bootstrap.css: Stylesheet for the Bootstrap Theme styles/jqx.classic.css: Stylesheet for the Classic Theme styles/jqx.darkblue.css: Stylesheet for the DarkBlue Theme styles/jqx.energyblue.css: Stylesheet for the EnergyBlue Theme styles/jqx.shinyblack.css: Stylesheet for the ShinyBlack Theme styles/jqx.office.css: Stylesheet for the Office Theme styles/jqx.metro.css: Stylesheet for the Metro Theme styles/jqx.metrodark.css: Stylesheet for the Metro Dark Theme styles/jqx.orange.css: Stylesheet for the Orange Theme styles/jqx.summer.css: Stylesheet for the Summer Theme styles/jqx.black.css: Stylesheet for the Black Theme styles/jqx.fresh.css: Stylesheet for the Fresh Theme styles/jqx.highcontrast.css: Stylesheet for the HighContrast Theme styles/jqx.blackberry.css: Stylesheet for the Blackberry Theme styles/jqx.android.css: Stylesheet for the Android Theme styles/jqx.mobile.css: Stylesheet for the Mobile Theme styles/jqx.windowsphone.css: Stylesheet for the Windows Phone Theme styles/jqx.ui-darkness.css: Stylesheet for the UI Darkness Theme styles/jqx.ui-lightness.css: Stylesheet for the UI Lightness Theme styles/jqx.ui-le-frog.css: Stylesheet for the UI Le Frog Theme styles/jqx.ui-overcast.css: Stylesheet for the UI Overcast Theme styles/jqx.ui-redmond.css: Stylesheet for the UI Redmond Theme styles/jqx.ui-smoothness.css: Stylesheet for the UI Smoothness Theme styles/jqx.ui-start.css: Stylesheet for the UI Start Theme styles/jqx.ui-sunny.css: Stylesheet for the UI Sunny Theme styles/images: contains images referenced in the stylesheet files Files for individual widgets. Include depending on project needs: jqx-all.js: All plug-ins and widgets jqxdata.js: Data Source plug-in jqxchart.js: Chart widget jqxgrid.js: Grid widget jqxgrid.sort.js: Grid Sort plug-in jqxgrid.filter.js: Grid Filter plug-in jqxgrid.grouping.js: Grid Grouping plug-in jqxgrid.selection.js: Grid Selection plug-in jqxgrid.columnsresize.js: Grid Columns Resize plug-in jqxgrid.columnsreorder.js: Grid Columns Reorder plug-in jqxgrid.pager.js: Grid Pager plug-in jqxgrid.edit.js: Grid Editing plug-in jqxgrid.storage.js: Grid Save/Load state plug-in jqxgrid.aggregates.js: Grid Aggregates plug-in jqxgauge.js: Radial and Linear Gauge widget jqxdatatable.js: DataTable widget jqxtreegrid.js: TreeGrid widget jqxrangeselector.js: RangeSelector widget jqxbuttons.js: Button, RepeatButton, SubmitButton & ToggleButton widgets jqxbulletchart.js: BulletChart widget jqxbuttongroup.js: Button group widget jqxswitchbutton.js: Switch Button widget jqxcalendar.js: Calendar widget jqxdatetimeinput.js: DateTimeInput widget jqxdockpanel.js: DockPanel widget jqxdropdownlist.js: DropDownList widget jqxcombobox.js: ComboBox widget jqxtabs.js: Tabs widget jqxtree.js: Tree widget jqxtreemap.js: TreeMap widget jqxcheckbox.js: CheckBox widget jqxradiobutton.js: RadioButton widget jqxexpander.js: Expander widget jqxlistbox.js: ListBox widget jqxmaskedinput.js: Masked TextBox widget jqxmenu.js: Menu widget jqxnavigationbar.js: NavigationBar widget jqxnotification.js: Notification widget jqxnumberinput.js: NumberInput TextBox widget jqxinput.js: TextBox widget jqxpanel.js: Panel widget jqxpopup.js: impements PopUp widget jqxprogressbar.js: ProgressBar widget jqxpasswordinput.js: Password input widget jqxscrollbar.js: ScrollBar widget jqxtooltip.js: ToolTip widget jqxrating.js: Rating widget jqxsplitter.js: Splitter widget jqxslider.js: Slider widget jqxwindow.js: Window widget jqxdocking.js: Docking widget jqxcolorpicker.js: Color Picker widget jqxdropdownbutton.js: DropDown Button widget jqxvalidator.js: Validation plug-in jqxdragdrop.js: DragDrop plug-in jqxknockout.js: Knockout integration plug-in jqxresponse.js: Response plug-in jqxangular.js: AngularJS integration plug-in

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值