dir.by  
  Поиск  
Компьютер, программы
ASP.NET MVC (Model-View-Controller website)
 Пример: Аутентификация (login/register/logout) в ASP.NET MVC используя аутентификацию форм FormsAuthentication.SetAuthCookie(model.Name, true); 
посмотрели 21668 раз
обновлено: 13 January 2019
Пример работает так:
• мы создаем таблицу в базе данных с полями login, password

при регистрации пользователя мы добавляем login, password в нашу таблицу базы данных.

при логине (пользователь вводит login и password).
Получаем введенный login, password и ищем в базе данных.
Если нашли значит пользователя будем логинить (сохраняем его в cookie через Аутентификация форм FormsAuthentication.SetAuthCookie(model.Name, true);

при logout мы удаляем пользовател из cookie
Шаг 1. Создаем новый ASP.NET MVC проект в Visual Studio 2017
Шаг 2. В web.config включаем аутентификацию форм
Внутри секции <system.web> добавим
<authentication mode="Forms">
     <forms name="cookies" timeout="2880" loginUrl="~/Account/Login" ></forms>
</authentication>
  Файл web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
     For more information on how to configure your ASP.NET application, please visit
     https://go.microsoft.com/fwlink/?LinkId=301880
-->

<configuration>
     <appSettings>
          <add key="webpages:Version" value="3.0.0.0"/>
          <add key="webpages:Enabled" value="false"/>
          <add key="ClientValidationEnabled" value="true"/>
          <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
     </appSettings>
     <system.web>
          <compilation debug="true" targetFramework="4.6.1"/>
          <httpRuntime targetFramework="4.6.1"/>
          <authentication mode="Forms">
               <forms name="cookies" timeout="2880" loginUrl="~/Account/Login" />
          </authentication>
     </system.web>
     <runtime>
          <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
               <dependentAssembly>
                    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
                    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
               </dependentAssembly>
               <dependentAssembly>
                    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
                    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
               </dependentAssembly>
               <dependentAssembly>
                    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
                    <bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0"/>
               </dependentAssembly>
          </assemblyBinding>
     </runtime>
     <system.codedom>
          <compilers>
               <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
               <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
          </compilers>
     </system.codedom>
</configuration>
Установив mode="Forms", мы тем самым подключаем аутентификацию форм.
name
имя для куки-набора. Значение по умолчанию - ".ASPXAUTH"
path
задает путь для куки-наборов. Значение по умолчанию - "/"
timeout
определяет срок действия куков в минутах
loginUrl
адрес для аутентификации пользователя. Значение по умолчанию - "~/Account/Login"
...
Шаг 3. Добавляем библиотеку Entity Framework используя NuGet
Шаг 4. Создаем соединиение с Базой данных Microsoft SQL Server в файле Web.config
Добавляем соединение <connectionStrings>...</connectionStrings> к Базе данных в файле Web.config
Новые добавленные строчки помеченные синим
  Файл web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
     For more information on how to configure your ASP.NET application, please visit
     https://go.microsoft.com/fwlink/?LinkId=301880
-->

<configuration>
     <configSections>
          <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
          <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
     </configSections>
     <appSettings>
          <add key="webpages:Version" value="3.0.0.0" />
          <add key="webpages:Enabled" value="false" />
          <add key="ClientValidationEnabled" value="true" />
          <add key="UnobtrusiveJavaScriptEnabled" value="true" />
     </appSettings>
     <system.web>
          <compilation debug="true" targetFramework="4.6.1" />
          <httpRuntime targetFramework="4.6.1" />
          <authentication mode="Forms">
               <forms name="cookies" timeout="2880" loginUrl="~/Account/Login" />
          </authentication>
     </system.web>
     <runtime>
          <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
               <dependentAssembly>
                    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
               </dependentAssembly>
               <dependentAssembly>
                    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
               </dependentAssembly>
               <dependentAssembly>
                    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                    <bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
               </dependentAssembly>
          </assemblyBinding>
     </runtime>
     <system.codedom>
     <compilers>
               <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
               <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
          </compilers>
     </system.codedom>
     <connectionStrings>
          <add name="MyConnection1" connectionString="Data Source=EVGENI\MSSQLSERVER2012;Initial Catalog=MyDatabase1;Integrated Security=True;" providerName="System.Data.SqlClient" />
     </connectionStrings>
     <entityFramework>
          <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
          <providers>
               <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
          </providers>
     </entityFramework>
</configuration>
На заметку!
Initial Catalog=MyDatabase1 это название базы данных. Если такое название не существует то новая база данных будет создана.
name="MyConnection1" пишем любой текст это имя соединения. Это имя соединения будем использовать в C# классах.
Data Source=EVGENIMSSQLSERVER2012 это имя сервера базы данных (SQL Server name). Сервер базы данных может находится локально или на другом компьютере. Имя сервера базы данных появляется при открытии SQL Server Management Studio (на картинке нарисовано).
Шаг 5. Добавим файл UserContext.cs в папку Models (класс User и класс UserContext для работы с Базой данных)
Нажмем правой клавишей мыши на папку "Models"AddNew Item
  C#     В файле UserContext.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data.Entity;

namespace WebApplication1.Models
{
     public class UserContext : DbContext
     {
          public UserContext() : base("MyConnection1")
          {
          }

          public DbSet<User> Users { get; set; }
     }

     public class User
     {
          public int Id { get; set; }
          public string Email { get; set; }
          public string Password { get; set; }
          public int Age { get; set; }
     }
}
Шаг 6. Добавим файл UserLoginRegister.cs в папку Models (класс UserLogin и класс UserRegister)
При логине в форме мы будем использовать
класс UserLogin

При регистрации в форме мы будем использовать
класс UserRegister

Добавим файл UserLoginRegister.cs в папку Models
  C#     В файле UserLoginRegister.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
     public class UserLogin
     {
          [Required]
          public string Name { get; set; }

          [Required]
          [DataType(DataType.Password)]
          public string Password { get; set; }
     }

     public class UserRegister
     {
          [Required]
          public string Name { get; set; }

          [Required]
          [DataType(DataType.Password)]
          public string Password { get; set; }

          [Required]
          [DataType(DataType.Password)]
          [Compare("Password", ErrorMessage = "Пароли не совпадают")]
          public string ConfirmPassword { get; set; }

          [Required]
          public int Age { get; set; }
     }
}
Шаг 7. Добавляем HomeController
Чтобы добавить контроллер в наш проект в окне Solution Explorer нажимаем правой клавишей мыши на
ControllersAddController
  C#     В файле HomeController.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
using System.Web.Security;

namespace WebApplication1.Controllers
{
     public class HomeController : Controller
     {
          public ActionResult Index()
          {
               return View();
          }

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

          [HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Login(UserLogin model)
          {
               if (ModelState.IsValid)
               {
                    // поиск пользователя в бд
                    User user = null;
                    using (UserContext db = new UserContext())
                    {
                         user = db.Users.FirstOrDefault(u => u.Email == model.Name && u.Password == model.Password);

                    }
                    if (user != null)
                    {
                         FormsAuthentication.SetAuthCookie(model.Name, true);
                         return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                         ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                    }
               }

               return View(model);
          }

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

          [HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Register(UserRegister model)
          {
               if (ModelState.IsValid)
               {
                    User user = null;
                    using (UserContext db = new UserContext())
                    {
                         user = db.Users.FirstOrDefault(u => u.Email == model.Name);
                    }
                    if (user == null)
                    {
                         // создаем нового пользователя
                         using (UserContext db = new UserContext())
                         {
                              db.Users.Add(new User { Email = model.Name, Password = model.Password, Age = model.Age });
                              db.SaveChanges();

                              user = db.Users.Where(u => u.Email == model.Name && u.Password == model.Password).FirstOrDefault();
                         }
                         // если пользователь удачно добавлен в бд
                         if (user != null)
                         {
                              FormsAuthentication.SetAuthCookie(model.Name, true);
                              return RedirectToAction("Index", "Home");
                         }
                    }
                    else
                    {
                         ModelState.AddModelError("", "Пользователь с таким логином уже существует");
                    }
               }

               return View(model);
          }

          public ActionResult Logoff()
          {
               FormsAuthentication.SignOut();
               return RedirectToAction("Index", "Home");
          }
     }
}
Шаг 8. Добавляем View с названием Index
Нажимаем правой клавишей мыши по методу Index в файле HomeController.cs и нажимаем на Add View ...
  В файле Index.cshtml напишем код
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
     <div>
          @if (User.Identity.IsAuthenticated)
          {
               @Html.ActionLink("logout...", "Logoff")
          }
          else
          {
               @Html.ActionLink("login", "Login")
               @Html.Label(" | ");
               @Html.ActionLink("register", "Register")
          }
     </div>
</body>
</html>
Шаг 9. Добавляем View с названием Login
  В файле Login.cshtml напишем код
@model WebApplication1.Models.UserLogin

@{
     ViewBag.Title = "Вход";
}

<h2>Вход</h2>


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

     <div class="form-horizontal">
          @Html.ValidationSummary(true)

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

          <div class="form-group">
               @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                    @Html.EditorFor(model => model.Password)
                    @Html.ValidationMessageFor(model => model.Password)
               </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>
}
Шаг 10. Добавляем View с названием Register
Нажимаем правой клавишей мыши по методу Register в файле HomeController.cs и нажимаем на Add View ...
  В файле Register.cshtml напишем код
@model WebApplication1.Models.UserRegister

@{
     ViewBag.Title = "Регистрация";
}

<h2>Регистрация</h2>


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

     <div class="form-horizontal">
          @Html.ValidationSummary(true)

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

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

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

          <div class="form-group">
               @Html.LabelFor(model => model.Age, new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                    @Html.EditorFor(model => model.Age)
                    @Html.ValidationMessageFor(model => model.Age)
               </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>
}
Шаг 11. Запускаем ASP.NET MVC приложение
Нажимаем вверху на зеленый треугольник
Все работает!
 
← Previous topic
What is authentication (login/register/logout) in the MVC ASP.NET?
 
Next topic →
What is authorization (admin/user/...) in the MVC ASP.NET?
 
Your feedback ... 2 Comments
guest
19 April 2020 12:38
Добрый день! При запуске приложения в браузере отображается: HTTP Error 404.0 - Not Found Разыскиваемый вами ресурс был удален, было изменено его имя или он временно недоступен.

Наиболее вероятные причины:
•Указанный каталог или файл не существует на данном веб-сервере.
•URL-адрес содержит орфографическую ошибку.
•Специальный фильтр или модуль, такой как URLScan, ограничивает доступ к файлу. Что можно предпринять:
•Создайте содержимое на веб-сервере.
•Проверьте URL-адрес веб-браузера.
•Чтобы получить дополнительные сведения об этой ошибке, проверьте журнал трассировки для невыполненных запросов и определите, какой модуль вызывает SetStatus.

Detailed Error Information: Module IIS Web Core Notification MapRequestHandler Handler StaticFile Error Code 0x80070002
admin (19 April 2020 13:07) Ошибка такая потому что:

1) Название контролера: CarController
метод контролера: Audi

не совпадают с путем в google chrome пример: http://localhost:8080/Car/VW   ← неправильно

Путь в google chrome должен быть такой: http://localhost:8080/Car/Audi   ← правильно

2) В visual studio в проекте view должна находиться тут:
Views/Car/Audi.cshtml
answer
guest
20 April 2020 11:21
Добрый день!
Подскажите, пожалуйста, возможно ли перенести аутентификацию на страницу aspx?
Если да, то как это сделать?

P.S. Большое спасибо за подробную и понятную инструкцию! В первый раз сталкиваюсь с аутентификацией и очень рада, что нашла этот форум.
admin (20 April 2020 12:17) Да, можно перенести аутентификацию на страницу aspx

Чтобы сделать аутентификацию на aspx странице нужно:

answer
admin (20 April 2020 13:38) Шаг 1.
В файл Web.config добавить пользователей
То есть для каждого ползователя добавить username и password

  Файл web.config
<authentication mode="Forms">

      <forms loginUrl="login.aspx">

            <credentials passwordFormat="SHA1">

                  <user name="user1" password="27CE4CA7FBF00685AF2F617E3F5BBCAFF7B7403C" />

                  <user name="user2" password="D108F80936F78DFDD333141EBC985B0233A30C7A" />

                  <user name="user3" password="7BDB09781A3F23885CD43177C0508B375CB1B7E9"/>

            </credentials>

      </forms>

</authentication>
answer
admin (20 April 2020 13:40) Шаг 2.

В aspx файле написать код
  Файл aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

public void Login_OnClick(object sender, EventArgs args)
{
      // проверяем пользователь на компьютере вввел правильный username и пароль?
      // введенный username и пароль проверяется с файлом из web.config
      if (FormsAuthentication.Authenticate(UsernameTextbox.Text, PasswordTextbox.Text))
      {
            // пользователь ввел правильный username и пароль

            // сохраняем username в cookie
            // то есть сохраняем username на компьютер у пользователя
            FormsAuthentication.SetAuthCookie(UsernameTextbox.Text, true);

            // написать код чтобы направить на главную страницу сайта
            // redirect to home page !!!!!!!
      }
      else
      {
             Msg.Text = "Login failed. Please check your user name and password and try again.";
      }
}


</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>
<title>Login</title>
</head>

<body>

      <form id="form1" runat="server">
            <h3>Login</h3>

            <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

            Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
            Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />

            <asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />

      </form>

</body>
</html>
answer
admin (20 April 2020 14:03) Шаг 3.

Чтобы пользователю сделать logout нужно взывать C# метод

  C#  
FormsAuthentication.SignOut();
answer
admin (20 April 2020 14:03) Шаг 4.

Чтобы узнать пользователь залогинен? нужно взывать C# метод:

  C#  
FormsAuthentication.GetAuthCookie(username, false)
answer
admin (20 April 2020 14:09) Готово! Вроди бы больше ничего не надо answer
guest (20 April 2020 15:30) Тогда использование таблицы в базе невозможно? answer
admin (21 April 2020 11:24) Чтобы сохранять в базу пользователя в aspx странице

1) не использовать
FormsAuthentication.Authenticate(UsernameTextbox.Text, PasswordTextbox.Text)

2) нужно написать свой метод C#:
bool IsValidDatabaseUser(string userName, string password);

В aspx файле написать код
  Файл aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

public void Login_OnClick(object sender, EventArgs args)
{
      // проверяем пользователь на компьютере вввел правильный username и пароль?
      if (IsValidDatabaseUser(UsernameTextbox.Text, PasswordTextbox.Text))
      {
            // пользователь ввел правильный username и пароль

            // то есть сохраняем username в cookie (на компьютер у пользователя)
            FormsAuthentication.SetAuthCookie(UsernameTextbox.Text, true);

            // написать код чтобы направить на главную страницу сайта
            // redirect to home page !!!!!!!
      }
      else
      {
             Msg.Text = "Login failed. Please check your user name and password and try again.";
      }
}


</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>
<title>Login</title>
</head>

<body>

      <form id="form1" runat="server">
            <h3>Login</h3>

            <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

            Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
            Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />

            <asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />

      </form>

</body>
</html>


Чтобы пользователю сделать logout нужно взывать C# метод
  C#  
FormsAuthentication.SignOut();


Чтобы узнать пользователь залогинен? нужно взывать C# метод:
  C#  
FormsAuthentication.GetAuthCookie(username, false)
answer
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
What is MVC in ASP.NET ?
Creating a new application ASP.NET MVC
Controller
Pass the data from the controller to the view in the MVC ASP.NET. Using ViewBag, ViewData, TempData, Model (strongly typed view)
View
What are Razor View and Operators in MVC ASP.NET
Create a variable and display it in View in the MVC ASP.NET
@using inside View in the MVC ASP.NET
@foreach(var item in arr) {...} inside the View in the MVC ASP.NET
@DateTime.Now inside the View in the MVC ASP.NET
How to find the name of the controller inside the View in the MVC ASP.NET
Display [DateTime | Date only | Time only] in the desired format in the MVC ASP.NET
Views
Strongly-typed-view in MVC ASP.NET
...
Master View using @RenderBody() in the MVC ASP.NET
Master View using @RenderBody() and additional sections @RenderSection in the MVC ASP.NET
...
Partial View in the MVC ASP.NET. Embed a partial representation @Html.Partial("My1") and @{ Html.RenderPartial("My1");}
When you click submit inside the partial view, the controller method is called ajax. The controller method should return PartialView(model) | ASP.NET MVC
...
Strongly-typed partial view in the MVC ASP.NET
Create the ViewModels folder. This is a good programming style for transferring data from the Controller to the View
Create the ViewModels folder. Create your class in the ViewModels folder. This is a good programming style for transferring data from the Controller to the View. Web Application ASP.NET MVC
Attributes. Use the attributes in the ViewModels (to show the combo buttons in the view). Using attributes in the Controller (to improve methods)
Attribute [Display(Name = "... ")] is described in the C# class and used in @Html.LabelFor, @Html.DisplayNameFor in the MVC ASP.NET
The attribute [Required(ErrorMessage = "Please enter a name")] is described for a property in the C# class and requires the property to be populated if the ErrorMessage error in the MVC ASP.NET is not filled in the screen
The attribute [Remote("IsValidAuthor", "Home", ErrorMessage = "Enter correct author of book")] is described for a property in a C# class and checks that property for correctness on the server via the IsValidAuthor method in conroller Home, if the method returns false, then there will be an ErrorMessage error on the screen in the MVC ASP.NET
The [HiddenInput(DisplayValue=false)] attribute is described in the C# class and is used in @Html.HiddenFor in the MVC ASP.NET
Routing
Links and redirects in the view
@Html.ActionLink inside the View in the MVC ASP.NET
@Html.RouteLink inside the View in the MVC ASP.NET
@Url.Action inside the View in the MVC ASP.NET
@Url.RouteUrl inside the View in the MVC ASP.NET
@Url.Content inside the View in the MVC ASP.NET
Bootstrap in MVC
Add and include Bootstrap (css, js files) to ASP.NET MVC project
JQuery in MVC
Connecting JQuery to ASP.NET MVC project
Using JQuery, we get the contents of the View in the MVC ASP.NET. Example: $.get("/Home/Index", function (data) {...}) ...
MVC AjaxExtensions class (asynchronous data retrieval)
Plugging jQuery & AJAX into ASP.NET MVC project
Using Ajax.ActionLink, get the contents of the View and insert it into the div in the MVC ASP.NET
Ajax object (this is the AjaxExtensions class) in MVC ASP.NET
Database (Entity Framework) in MVC ASP.NET
Entity Framework in the ASP.NET MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
Authentication (login/register/logout)
What is authentication (login/register/logout) in the MVC ASP.NET?
Example: Authentication (login/register/logout) in MVC ASP.NET using FormsAuthentication.SetAuthCookie(model. Name, true);
Authorization (admin/user/...)
What is authorization (admin/user/...) in the MVC ASP.NET?
Example: Authorization (admin/user/...) in MVC ASP.NET using the RoleProvider role provider
Writing the appendix "Planning tasks" in the MVC ASP.NET
Creating an empty application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Adding Bootstrap & jQuery libraries to the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
Create a master view (main menu & button login using Bootstrap) in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
Add the "Home" controller and the "Index" view (the main page in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Add the Entity Framework library and create a connection to the Database in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
Authentication (login/register/logout) in the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
Add the class "Task" to save tasks, tasks to the database in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Adding nUnit in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Additional topics, questions
Why is MVC ASP.NET better ASP.NET Web Forms?
Choosing between ASP.NET Core and ASP.NET?
How to choose an Internet browser to run a .NET project in it
How do I find the local address and port of your ASP.NET MVC application?
Scriptsindex.d.ts(8,1): error TS1008: Build:Unexpected token; "module, class, interface, enum, import or statement" expected. Scriptsindex.d.ts(8,13): error TS1005: Build:";" expected. in Visual Studio 2017 in the ASP.NET MVC app
Error "unable to connect to web server "iis express" | ASP.NET MVC | Visual Studio 2017
Error "This site can"t be reached" when run ASP.NET application | Solution: Recreate the Self-Signed HTTPS Certificate for localhost in IIS Express
WWW Sites to Learn ASP.NET MVC
Sites to learn ASP.NET MVC

  Ваши вопросы присылайте по почте: info@dir.by