Learn MVC IN ASP
1.0.0
感謝您的閱讀,祝您在任何想要使用 ASP.NET 的平台或 Web 應用程式上好運。
您可以透過電子郵件[email protected]
與我聯繫。認識我的人可以透過適當的媒介與我聯繫。
或者,您可以在 Discord 上透過以下帳號聯絡我: #1337
。
Web 應用程式的原始程式碼可以在這個 Repo 中找到,只需查看即可。本自述文件中解釋的所有內容都是原始程式碼中的所有內容。
ASP 基礎知識 (.NET)
型號
路線
RouteConfig
檔。控制器
意見
資料庫 [即將]
.cshtml
- CSharpHTML 格式的 HTML 或範本檔案。將有一個名為“共享”的預設資料夾。該資料夾包含您的範本文件/佈局主文件以及錯誤文件。 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 >