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. 运用<body>属性,渲染页面效果

    新建一个HTML5文件,为<body>标签添加样式,代码如下: 01 <!doctype html> 02 <html> 03 <head> 04 &l ...

  2. 扩展银行项目,添加一个(客户类)Customer类。Customer类将包含一个Account对象。

    练习目标-使用引用类型的成员变量:在本练习中,将扩展银行项目,添加一个(客户类)Customer类.Customer类将包含一个Account对象. 任务 在banking包下的创建Customer类 ...

  3. 怎样批量删除PDF文件中的注释

    日常我们在阅读一些PDF文章时候,我们会发现有些PDF文章带有非常多的注释,显得非常不美观,影响了阅读体验.那么PDF文章里的批注应该怎么进行删除呢?怎样批量删除PDF文件中的注释?   操作教程: ...

  4. 关于MySQL,Oracle和SQLServer的特点以及之间区别

    关系型数据库:是指采用了关系模型来组织数据的数据库.简单来说,关系模型指的就是二维表格模型,而一个关系型数据库就是由二维表及其之间的联系组成的一个数据组织. 非关系型数据库:非关系型数据库严格上说不是 ...

  5. 关于java中的继承

    我们都知道Java中的继承是复用代码.扩展子类的一种方式,继承使得Java中重复的代码能够被提取出来供子类共用,对于Java程序的性能以及修改和扩展有很大的意义,所以这是一个非常重要的知识点. 那么对 ...

  6. git_安装与配置

    安装 windows平台安装 在windows平台安装git,需要下载exe.文件,下载地址:https://gitforwindows.org/,双击下载的.exe文件,按照提示进行安装,安装完成后 ...

  7. 15.5.2 【Task实现细节】骨架方法的结构

    尽管骨架方法中的代码非常简单,但它暗示了状态机的职责.代码清单15-11生成的骨架方 法如下所示: [DebuggerStepThrough] [AsyncStateMachine(typeof(De ...

  8. matlab 读取输入数组

    In an assignment A(I) = B, the number of elements in B and I must be the same MATLAB:index_assign_el ...

  9. dup、文件锁、库函数、函数调用(day07)

    一.lseek()重新定位文件的读写位置. #include <sys/types.h> #include <unistd.h> off_t lseek(int fd, off ...

  10. 《奋斗吧!菜鸟》 第八次作业:Alpha冲刺 Scrum meeting 5

    项目 内容 这个作业属于哪个课程 任课教师链接 作业要求 https://www.cnblogs.com/nwnu-daizh/p/11012922.html 团队名称 奋斗吧!菜鸟 作业学习目标 A ...