Закрыть
×
=0) { let js = text.slice(pos1, pos2); + '<\/' + "script" + '>'; arrText.push(js); // next pos1 = pos2; continue; } } } break; } return arrText; } function OpenDialog(parentDiv, urlContent) { parentDiv = document.getElementById('modal-background'); // new !!!!!!! parentDiv.appendChild(document.getElementById('modal-template')); document.getElementById('modal-background').style.display = "flex"; // !!!!! block document.getElementById('modal-template').style.display = "flex"; // !!!!! document.getElementById('modal-body').innerHTML = ""; post_url(urlContent, "", function(text_from_server) { var element = document.getElementById('modal-body'); element.innerHTML = text_from_server; // add scripts var arrJSText = get_scripts(text_from_server); for (var i=0; i
dir.by
Праздники ...
Праздники ...
День города Минска (2-ая суббота сентября) (9 и 10 сентября 2023)
Концерты, выставки ...
Концерты, выставки ...
Вадим Самойлов "Агата Кристи"|||г. Минск 19 декабря 2026
Афишу
Спорт занятия ...
Спорт занятия ...
Настольный теннис
Спорт занятие
Компьютер, программы...
Компьютер, программы...
Объявления ...
Объявления ...
Аренда самосвалов
Объявление
Новости ...
Новости ...
Форум ...
Форум ...
обсуждение...
Поиск
Концерты
Спорт
Форум
Компьютер
Компьютер, программы
→
ASP.NET MVC (Model-View-Controller website)
Создаем новое приложение ASP.NET MVC
посмотрели
12172
раз
обновлено: 18 May 2020
Скачать пример:
MyAspNetWebApplication.zip ...
План (6 шагов)
Шаг 1.
Открываем Visual Studio
Шаг 2.
Создаем пустое ASP.NET MVC приложение
Шаг 3.
Добавляем первый Controller
Шаг 4.
Добавляем первое View
Шаг 5.
Добавляем текст "Hello! World!!!" во View
Шаг 6.
Запускаем ASP.NET MVC приложение
Шаг 1. Открываем Visual Studio
If you do not have
Visual Studio
installed you need
install Visual Studio...
Open
Visual Studio 2022
or
Open
Visual Studio 2019
Шаг 2. Создаем пустое ASP.NET MVC приложение
Нажимаем в меню:
File
→
New
→
Project
→
Visual C#
→
ASP.NET Web Application
Нажимаем
OK
Проект ASP.NET MVC создался!
Запускаем проект
Нажимаем вверху на зеленый треугольник
Ошибка!
Чтобы проект запустился нужно чтобы в проекте были:
• один или больше
Controller
• один или больше
View
После создания нового проекта
Controller
и
View
отсутствуют.
Controller
и
View
сейчас создадим.
Шаг 3. Добавляем первый Controller
В архитектуре
ASP.NET MVC
входящие запросы обрабатываются
контроллерами
.
Контроллер
это обычный
C# класс
(как правило, наследуются от
System.Web.Mvc.Controller
, базовый класс контроллеров).
В
ASP.NET MVC
контроллеры
находятся в папке под названием
Controllers
, которую
Visual Studio
создала для нас при создании проекта.
Чтобы добавить контроллер в наш проект
в окне
Solution Explorer
нажимаем правой клавишей мыши на
Controllers
→
Add
→
Controller
Назовите контроллер
HomeController
В ASP.NET MVC есть соглашение 1:
Имена, которые мы даем контроллерам, должны заканчиваться словом
Controller
Нажимаем
Add
и будет создан
HomeController.cs
У нас добавился
Controller
Теперь если нажимем вверху на зеленый треугольник т.е. запустим приложение
На экране увидим ошибку
Ошибка!
Потому что наш
Contoller
пытается найти
View
(представление) и не находит.
Это сообщение об ошибке очень полезно.
В сообщении указано, что
ASP.NET MVC
не смог найти
View
(представление) для нашего
метода
, а также показано, где искал.
В ASP.NET MVC есть соглашение 2:
View
(представление) связано с
методом
в
Controller
при помощи
имени
.
То есть
название класса View
должно совпадать с
названием метода
в
Controller
На заметку!
В словесной терминалогии
метод
в
Controller
называется
метод действия
Наш
Controller
называется
Home
,
Наш
метод действия
называется
Index
C#
Вспомним наш контроллер файл
HomeController.cs
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
namespace
WebApplication2.Controllers
{
public
class
HomeController
: Controller
{
public
ActionResult
Index
()
{
return
View();
}
}
}
Объяснение!
Наш класс называется
HomeController
поэтому мыслено убираем слово
Controller
и получаем что наш контроллер называется
Home
Внутри нашего класса
HomeController
есть метод
Index
это и есть название
метода действия
Шаг 4. Добавляем первое View
Нажимаем правой клавишей мыши по методу
Index
в файле
HomeController.cs
и нажимаем на
Add View ...
Снимем галочку [ ]
Use a layout or master page
.
Нажимаем
Add
Visual Studio
в папке
Views/Home
создал новый файл
Index.cshtml
Видим что файл содержит
стандартный HTML
. Исключение составляет лишь код:
@{
Layout = null;
}
Данное выражение будет дополнительно разобрано
движком Razor
.
Шаг 5. Добавляем текст "Hello! World!!!" во View
Html
Файл
Index.cshtml
@{
Layout = null;
}
<!DOCTYPE
html>
<html>
<head>
<meta
name=
"viewport"
content=
"width=device-width"
/>
<title>
Index
</title>
</head>
<body>
<div>
Hello! World!!!
</div>
</body>
</html>
Открываем
Index.cshtml
это в папке
Views/Home
и пишем
"Hello! World!!!"
Шаг 6. Запускаем ASP.NET MVC приложение
Нажимаем вверху на зеленый треугольник
Откроется страница в браузере и мы увидим текст "Hello World!!!"
Итог
Вы заметили, что пример запустился с адресом:
localhost:1764/Home/Index
localhost:1764
Это имя сервера и порт
localhost
это локальный компьютер
1764
это номер порта
Home
Это класс контроллера, который по полному называется
HomeController
Index
Это название
метода контроллера
C#
Наш контроллер файл
HomeController.cs
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
namespace
WebApplication2.Controllers
{
public
class
HomeController
: Controller
{
public
ActionResult
Index
()
{
return View()
;
}
}
}
return View
вызовет Views/
Home
/
Index
.cshtml файл
То есть
метод контроллера
вызовет соответствующее
View
(представление)
Вот наше
представление
(в виде html файла)
Html
Views/Home/
Index.cshtml
@{
Layout = null;
}
<!DOCTYPE
html>
<html>
<head>
<meta
name=
"viewport"
content=
"width=device-width"
/>
<title>
Index
</title>
</head>
<body>
<div>
Hello! World!!!
</div>
</body>
</html>
Скачать пример
MyAspNetWebApplication.zip ...
← Previous topic
What is MVC in ASP.NET ?
Next topic →
Pass the data from the controller to the view in the MVC ASP.NET. Using ViewBag, ViewData, TempData, Model (strongly typed view)
Your feedback ... Comments ...
Your Name
Your comment
(www links can only be added by a logged-in user)
+ Picture
•
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