Learn MVC IN ASP
1.0.0
읽어주셔서 감사합니다. ASP.NET을 사용하려는 플랫폼이나 웹앱에 행운이 있기를 바랍니다.
이메일 [email protected]
통해 저에게 연락하실 수 있습니다. 나를 IRL/개인으로 아는 사람들은 적합한 매체를 통해 나에게 연락할 수 있습니다.
또는 Discord에서 #1337
핸들을 사용하여 저에게 연락할 수 있습니다.
웹 앱의 소스 코드는 이 Repo에서 사용할 수 있습니다. 확인해 보세요. 이 README 파일에 설명된 모든 내용은 소스 코드 내부의 모든 내용입니다.
ASP(.NET)의 기본
모델
노선
RouteConfig
파일.컨트롤러
조회수
데이터베이스 [ 곧 ]
.cshtml
- CSharpHTML 형식의 HTML 또는 템플릿 파일이 포함됩니다. "Shared"라는 기본 폴더가 있습니다. 이는 템플릿 파일/레이아웃 마스터 파일과 오류 파일이 포함된 폴더입니다. namespace MVCTutorial . Models
{
public class User
{
/*
* Getter and Setter
* Usually handled by the Model and Controller for Parameter binding
* -----
* get - Allows you to get this parameter anywhere
* set - Allows the auto-binding to happen when the parameter injected matches the requirement
* -----
* However, this Model is usually referred to an Object. An Object is a "package" or "stack" of list (imagine)
* which contains the data that you need. Let alone if it's extracted from a SQL Database (MS SQL, MS Access, SQL Server, etc)
* A Model doesn't ONLY Store data, but it also notifies any new changes to the Controller or View. Thus, that's the point of "Notifier".
*
* --- DIVING INTO MODEL ---
* public "int" Id
*
* The Type Casting of "int" can be replaced with other Type Castings as well.
* Example:
* public string {}
* public bool {}
* public char {}
* public dynamic {}
* public double {}
* public enum {}
* public float {}
*
* ----
* LONG STORY CUT SHORT
* A Model represents your data structures. Typically your model classes with contain functions that help you create, read, update, delete (CRUD) information in your Database.
*/
public int Id { get ; set ; }
public string username { get ; set ; }
}
}
RouteConfig
파일. using System . Web . Mvc ;
using System . Web . Routing ;
namespace MVCTutorial
{
public class RouteConfig
{
public static void RegisterRoutes ( RouteCollection routes )
{
// This means to ignore weird routes which "may" expose the Web App.
// REGEX is enforced
routes . IgnoreRoute ( "{resource}.axd/{*pathInfo}" ) ;
}
}
}
using System . Web . Mvc ;
using System . Web . Routing ;
namespace MVCTutorial
{
public class RouteConfig
{
public static void RegisterRoutes ( RouteCollection routes )
{
// This means to ignore weird routes which "may" expose the Web App.
// REGEX is enforced
routes . IgnoreRoute ( "{resource}.axd/{*pathInfo}" ) ;
// Default Fallback Route (Basic Routing)
// Parameters:
// name: - This means the name of the Route, HAS TO BE UNIQUE. "Default" will be used on Error.
// url: - The URL that it needs to be mapped and matched, ALL URL will pass this. {id} means a basic 1 param pass, we'll go through this in Controller section.
// defaults - The controller for the Route (An explicit object has to be passed.)
// - UrlParameter.Optional means "If the Controller wants this ID, it can take it. Otherwise, it's okay"
// ----------
routes . MapRoute (
name : "Default" ,
url : "{controller}/{action}/{id}" ,
defaults : new { controller = "Home" , action = "Index" , id = UrlParameter . Optional }
) ;
// ----------
}
}
}
using System . Web . Mvc ;
using System . Web . Routing ;
namespace MVCTutorial
{
public class RouteConfig
{
public static void RegisterRoutes ( RouteCollection routes )
{
// This means to ignore weird routes which "may" expose the Web App.
// REGEX is enforced
routes . IgnoreRoute ( "{resource}.axd/{*pathInfo}" ) ;
// Default Fallback Route (Basic Routing with Route Constraints)
// Route constraints mean Type Casting and filtering a URL with specific type of input you want with REGEX.
// NOTE: If you add ? behind your constraint, it means the valid can be there or not be there. Tentative param.
// "\d{2}" means I only want 2 numbers or characters for the ID. "\d" is just a convention for REGEX.
// You can view all of them here: https://www.tektutorialshub.com/asp-net-core/asp-net-core-route-constraints/
// ----------
routes . MapRoute (
name : "Default" ,
url : "{controller}/{action}/{id:int?}" ,
defaults : new { controller = "Home" , action = "Index" , id = UrlParameter . Optional } ,
constraints : new { id = " \ d{2}" }
) ;
// ----------
}
}
}
using System . Web . Mvc ;
using System . Web . Routing ;
namespace MVCTutorial
{
public class RouteConfig
{
public static void RegisterRoutes ( RouteCollection routes )
{
// Advanced Routing
// With only this line, it gets the [Route()] typecasting and uses that as the Route. This is the power of a MVC.
routes . MapMvcAttributeRoutes ( ) ;
}
}
}
using System ;
using System . Collections . Generic ;
using System . Linq ;
using System . Web ;
using System . Web . Mvc ;
using System . Web . Mvc . Ajax ;
using MVCTutorial . Models ;
namespace MVCTutorial . Controllers
{
public class HomeController : Controller
{
/* Your Methods */
}
}
using System ;
using System . Collections . Generic ;
using System . Linq ;
using System . Web ;
using System . Web . Mvc ;
using System . Web . Mvc . Ajax ;
using MVCTutorial . Models ;
namespace MVCTutorial . Controllers
{
public class HomeController : Controller
{
/*
* ActionResult - This is mostly used every time, this is a very powerful cast where you can return anything.
* ViewResult - Only can return View()
* ContentResult - Only can return Content(); This means only plain text can be returned on the View.
* EmptyResult - Returns empty result, mostly empty page unless handled.
* JsonResult - Returns Json() object
* RedirectResult - Redirects to a Controller or Page
* FileStreamResult - Returns a FileStream for CRUD with a File.
* Example: public ViewResult MethodName() { }
*/
public ViewResult Index ( )
{
return View ( ) ;
}
// ContentResult Route
public ContentResult Users ( )
{
return Content ( "I am users" ) ;
}
}
}
using System ;
using System . Collections . Generic ;
using System . Linq ;
using System . Web ;
using System . Web . Mvc ;
using System . Web . Mvc . Ajax ;
using MVCTutorial . Models ;
namespace MVCTutorial . Controllers
{
public class HomeController : Controller
{
// GET /User/1 or GET /User?id=1
// Routes in this method are Case Sensitive!
public ContentResult User ( int id )
{
return Content ( $ "ID: { id } " ) ;
}
}
}
using System ;
using System . Collections . Generic ;
using System . Linq ;
using System . Web ;
using System . Web . Mvc ;
using System . Web . Mvc . Ajax ;
using MVCTutorial . Models ;
namespace MVCTutorial . Controllers
{
public class HomeController : Controller
{
// This means https://domain.com/ aka GET /
// The main landing route for ANY Site. It always starts from '/'
[ Route ( "" ) ] // <---- TAKE NOTE!
public ViewResult Index ( )
{
return View ( ) ;
}
// ContentResult Route
// GET /users
[ Route ( "users" ) ]
public ContentResult Users ( )
{
return Content ( "I am users" ) ;
}
// Route with Parameters
// Type Casting means it only will accept int
// GET /users/edit/1
[ Route ( "users/edit/{id:int}" ) ]
public ContentResult Edit ( int id )
{
return Content ( $ "User ID: { id } " ) ;
}
}
}
using System ;
using System . Collections . Generic ;
using System . Linq ;
using System . Web ;
using System . Web . Mvc ;
using System . Web . Mvc . Ajax ;
using MVCTutorial . Models ;
namespace MVCTutorial . Controllers
{
public class HomeController : Controller
{
// Passing Parameters to View using ViewBag
// '?' means tentative variable. Can be NULL or present.
[ Route ( "page/{name?}" ) ]
public ViewResult Page ( string name )
{
if ( string . IsNullOrWhiteSpace ( name ) )
{
name = "Hello World" ;
}
ViewBag . Title = name ;
return View ( ) ;
}
}
}
using System ;
using System . Collections . Generic ;
using System . Linq ;
using System . Web ;
using System . Web . Mvc ;
using System . Web . Mvc . Ajax ;
using MVCTutorial . Models ;
namespace MVCTutorial . Controllers
{
public class HomeController : Controller
{
// Passing a Model into the View with Data. This is super convenient
// GET /users/return/one
[ Route ( "users/return/one" ) ]
public ViewResult ReturnUser ( )
{
// Initialize a User Model first with Data as below
var user = new User ( ) { Id = 1 , username = "InspectorGadget" } ;
// Now, just pass this bad boy into the View
return View ( user ) ;
}
}
}
using System ;
using System . Collections . Generic ;
using System . Linq ;
using System . Web ;
using System . Web . Mvc ;
using System . Web . Mvc . Ajax ;
using MVCTutorial . Models ;
namespace MVCTutorial . Controllers
{
public class HomeController : Controller
{
// Passing a Model <List> into the View with Data. This is super convenient
// GET /users/return/many
[ Route ( "users/return/many" ) ]
public ViewResult ReturnUsers ( )
{
// Multiple Objects <List>
var users = new UsersViewModel
{
Users = new List < User >
{
new User
{
Id = 1 ,
username = "InspectorGadget"
} ,
new User
{
Id = 2 ,
username = "Juice WRLD"
}
}
} ;
return View ( users ) ;
}
}
}
/Views/Shared/_Layout.cshtml
파일을 열면. 여기에 그 예가 있습니다.RenderBody()
는 특정 템플릿 파일(뷰)이 코드 블록으로 렌더링되는 곳입니다. <!DOCTYPE html >
< html >
< head >
<!--
This Layout Template has ViewBag where it appends and binds the parameters from the View or Controller.
Magic? No, just a convenient way!
-->
< title > @ViewBag.Title </ title >
< meta charset =" utf-8 " />
</ head >
< body >
@RenderBody()
</ body >
</ html >
<!--
Any HTML entered here gets auto rendered into the <body></body> of your Layout Template File.
-->
<!--
Have a custom template?
Sure, you can add it as well
-->
@* @{ *@
@* Layout = "~/Views/Shared/_Layout.cshtml"; *@
@* } *@
<!--
Do you want Dynamic Value Binding?
Like page title, etc?
Yes, you can too!
ASP uses @{} syntax, it's exactly like a templating engine. If you are used to Flask's Jinja or Laravel's Blade, they are the same.
ASP also uses ViewBag, this is used to pass parameters into the View asynchronously without impacting the view's performance.
-->
@{
ViewBag.Title = "Home";
}
<p>Hello World. This is the main page. Now check the Page Title on the top! Is it the same with ViewBag?</p
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
< h2 > Wazzup! </ h2 >
@{
ViewBag.Title = "Make User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
< h2 > Me is gae </ h2 >
@model MVCTutorial.Models.User
@{
ViewBag.Title = "Make User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
< h2 > @Model.username with the ID of @Model.Id </ h2 >