https://docs.asp.net/en/latest/tutorials/first-mvc-app/controller-methods-views.html

We have a good start to the movie app, but the presentation is not ideal. We don’t want to see the time (12:00:00 AM in the image below) and ReleaseDate should be two words.

Open the Models/Movie.cs file and add the highlighted lines shown below:

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; }
}

using System.ComponentModel.DataAnnotations;

We’ll cover DataAnnotations in the next tutorial.

The Display attribute specifies what to display for the name of a field (in this case “Release Date” instead of “ReleaseDate”).

The DataType attribute specifies the type of the data, in this case it’s a date, so the time information stored in the field is not displayed.

Browse to the Movies controller and hold the mouse pointer over an Edit link to see the target URL.

The EditDetails, and Delete links are generated by the MVC Core Anchor Tag Helper in theViews/Movies/Index.cshtml file.

<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files.

In the code above, the AnchorTagHelper dynamically generates the HTML href attribute value from the controller action method and route id.

You use View Source from your favorite browser or use the F12 tools to examine the generated markup.

The F12 tools are shown below.

Chrome浏览器,在界面上右键,检查:然后会弹出一个浏览界面,左上角的指针图标,单击之后,移动到页面上,会随着移动而展开html

Recall the format for routing set in the Startup.cs file.

 app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

ASP.NET Core translates http://localhost:1234/Movies/Edit/4 into

a request to the Edit action method of the Movies controller with the parameter ID of 4.

(Controller methods are also known as action methods.)

Tag Helpers are one of the most popular new features in ASP.NET Core. See Additional resources for more information.

Open the Movies controller and examine the two Edit action methods:

// GET: Movies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
} var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
if (movie == null)
{
return NotFound();
}
return View(movie);
} // POST: Movies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Genre,Price,ReleaseDate,Title")] Movie movie)
{
if (id != movie.ID)
{
return NotFound();
} if (ModelState.IsValid)
{
try
{
_context.Update(movie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(movie);
}

The [Bind] attribute is one way to protect against over-posting.

You should only include properties in the [Bind] attribute that you want to change.

See Protect your controller from over-posting for more information.

ViewModels provide an alternative approach to prevent over-posting.

Notice the second Edit action method is preceded by the [HttpPost] attribute.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Genre,Price,ReleaseDate,Title")] Movie movie)
{
if (id != movie.ID)
{
return NotFound();
} if (ModelState.IsValid)
{
try
{
_context.Update(movie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(movie);
}

The HttpPostAttribute attribute specifies that this Edit method can be invoked only for POST requests.

You could apply the [HttpGet] attribute to the first edit method, but that’s not necessary because [HttpGet] is the default.

The ValidateAntiForgeryTokenAttribute attribute is used to prevent forgery of a request and is paired up with an anti-forgery token generated in the edit view file (Views/Movies/Edit.cshtml).

The edit view file generates the anti-forgery token with the Form Tag Helper.

<form asp-action="Edit">

The Form Tag Helper generates a hidden anti-forgery token that must match the[ValidateAntiForgeryToken] generated anti-forgery token in the Edit method of the Movies controller.

For more information, see 

Controller methods and views的更多相关文章

  1. 010.Controller methods and views --【控制器方法与视图】

    Controller methods and views 控制器方法与视图 2017-3-7 9 分钟阅读时长 作者 By Rick Anderson We have a good start to ...

  2. Spring MVC @RequestMapping Annotation Example with Controller, Methods, Headers, Params, @RequestParam, @PathVariable--转载

    原文地址: @RequestMapping is one of the most widely used Spring MVC annotation.org.springframework.web.b ...

  3. ASP.NET Core 中文文档 第二章 指南(4.6)Controller 方法与视图

    原文:Controller methods and views 作者:Rick Anderson 翻译:谢炀(Kiler) 校对:孟帅洋(书缘) .张仁建(第二年.夏) .许登洋(Seay) .姚阿勇 ...

  4. 004.Create a web app with ASP.NET Core MVC using Visual Studio on Windows --【在 windows上用VS创建mvc web app】

    Create a web app with ASP.NET Core MVC using Visual Studio on Windows 在 windows上用VS创建mvc web app 201 ...

  5. 【IOS笔记】View Controller Basics

    View Controller Basics   视图控制器基础 Apps running on iOS–based devices have a limited amount of screen s ...

  6. 2.Adding a Controller

    MVC stands for model-view-controller.  MVC is a pattern for developing applications that are well ar ...

  7. View Controller Programming Guide for iOS---(二)---View Controller Basics

    View Controller Basics Apps running on iOS–based devices have a limited amount of screen space for d ...

  8. View Controller Programming Guide for iOS---(一)---About View Controllers

    About View Controllers View controllers are a vital link between an app’s data and its visual appear ...

  9. Understanding Models, Views, and Controllers (C#)

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models- ...

随机推荐

  1. .net core2.0 中使用aspectcore实现aop

    一.新建一个web application项目 1.1.添加AspectCore.Extensions.DependencyInjection引用 二.实现AbstractInterceptorAtt ...

  2. 《java数据结构与算法》系列之“开篇”

    大学的时候学习数据结构,当时吧虽然没挂这门课,但是确实学的不咋地,再但是其实自己一直都觉得数据结构很重要,是基础,只有基础好了,后面的路才能走的更好. 懒惰真的是天下的罪恶之源.所以一直到现在都毕业了 ...

  3. 使用pelican创建静态博客

    创建工作目录 首先使用pip安装pelican和markdown pip install pelican markdown 然后创建目录 mkdir my_blog 接着进入目录cd my_blog, ...

  4. mongodb 下载与安装文档

    MongoDB数据库安装及配置环境(windows10系统)   windows10系统下MongoDB的安装及环境配置: MongoDB的安装 下载地址: https://www.mongodb.c ...

  5. THREE.js代码备份——webgl - materials - cube refraction [balls](以上下左右前后6张图片构成立体场景、透明球体效果)

    <!DOCTYPE html> <html lang="en"> <head> <title>three.js webgl - ma ...

  6. 【Python基础】while循环语句

    Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while 判断条件: 执行语句…… 执行语句可以是单个语句或语句 ...

  7. Hadoop-2.2.0在Unbuntu ADM64中需要重新编译Native Lib

    通过:cat /etc/issue 查看当前系统版本: Ubuntu 12.04.3 通过:uname -ar 查看更想起信息: Linux ubuntu-236 3.8.0-29-generic # ...

  8. python从TXT创建PDF文件——reportlab

    使用reportlab创建PDF文件电子书一般都是txt格式的,某些电子阅读器不能读取txt的文档,如DPT-RP1.因此本文从使用python实现txt到pdf的转换,并且支持生成目录,目录能够生成 ...

  9. TextInputLayout使用时各个地方的字体颜色

    我们现在在做Android端的输入框时,要具备如下功能: 默认提示获取焦点时提示上移至输入框顶部获取焦点时输入框有提示错误时增加错误提示直接上图: 默认情况: 获取焦点时: 开始输入文字时: 有错误时 ...

  10. spring boot jpa 无法使用findOne

    (findOne(id))说我无法转换成相应的类型,换一种即可,如下: user = userRepository.findOne(id);//spring 2.x用不了 @GetMapping(&q ...