0% found this document useful (0 votes)
14 views15 pages

Dotnet Core Whole Theory

The document outlines the process of routing in ASP.NET, including middleware setup, controller routing, and various methods for passing data from controllers to views such as ViewData, ViewBag, TempData, and Strongly Typed Views. It also discusses the repository pattern for data management, session handling, form validations, and the use of partial views for creating reusable components. Additionally, it covers the integration of Entity Framework for database connectivity and the necessary steps for setting up migrations and connection strings.

Uploaded by

Shahzaad Vinad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views15 pages

Dotnet Core Whole Theory

The document outlines the process of routing in ASP.NET, including middleware setup, controller routing, and various methods for passing data from controllers to views such as ViewData, ViewBag, TempData, and Strongly Typed Views. It also discusses the repository pattern for data management, session handling, form validations, and the use of partial views for creating reusable components. Additionally, it covers the integration of Entity Framework for database connectivity and the necessary steps for setting up migrations and connection strings.

Uploaded by

Shahzaad Vinad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

ROUTING WITH CUSOMT OPTIONS

1.​ program.cs
Add this middleware
app.MapContorller()

2.​ Contorller
Add [Route(“URL”)] above the method which needs to be called for that url

Ex [Route(“home”]
Public IActionResult Data(){ return View() } → this will show view related to home
[Route(“home/about”)]
Public IActionResult RandomName(){ return View() } ⇒ swill show about page

Adding [Route(“Home”)] above Contrl class, will help by elimantig the home name from other
routes below
I.e [Route(“Home”)]
Public class Homecntr : Cntrl{
[Route(“”)]
Public IActionResult Index(){ return View() }
[Route(“about”)]
Public IActionResult About(){ return View() }
}

MAP FOR ROUTING


Map(“/Home”, ()=> “Hello from Home”); - wrks w all mthds
MapGet(“/Home”, ()=> “Hello from Home get”); wrks w only get
MapPost(“/Home”, ()=> “Hello from Home post”); wrks w only post
MapPut(“/Home”, ()=> “Hello from Home put”); wrks w only put
MapDelete(“/Home”, ()=> “Hello from Home del”); wrks w only del method

Routing using UseRouting()


app.UseRouting();
app.UseEndpoints(endpoint => {
endpoint.MapGet(‘/Home”, async (cntx) =>
{ await cntx.Response.WriteAsync(‘this works “); }
endpoint.MapPut(“/Home”, async (cntx)=>
{ await cntx.Response.Wreitasync(“tis wrks”); }
} );
});
localhost:port/ < — in this case this code wl execute
app.Run( async ( HttpCntx cntx ) =>
{
Await cntx.Response.WriteAsync(‘First page w/o any appended url”);
}

RAZOR
Inline expressions starts with @
Enclose code blacks betwen @{ and }
Vars are decl with var keyword
Enclose strings in quotation marks

Layout View = Master Page – starts w _ naming convection - _Layout.cshtml


What is Master Page ?
Header
Center data → content changes
Footer
Common view is defined on master page, and changin are made separately and master
pg is connected to those separate files, via child relation. I.e index pg is child of master
pg, and Master pg is parent of index pg. We use Layout Property in child pages.

Master pg
<body>
<header>ahha</header>
@RenderBody()
<footer>asdf</footer>
</body>

Index pg
@{ Layout = “~/path to master pg “; }
<h2> this is index pg </h2>

Thats how yo connect child Indepg to parent Masterpg


PASSING DATE FROM CNTRL TO VIEW
4 METHODS - ViewData, ViewBag, TempData, StronglyTypedViews

1.VIEWDATA —
ViewData[“Key”] = <Value>; in cntrl
Ex ViewData[“data1”] = “program”;
@ViewData[“Key”] in Razor or view
Ex @ViewData[‘data1’]
For sending arrays
String[[ arr = {“adsf”,”afd”,”adf”};
ViewData[‘data3’] = arr;
In View, @{ foreach( var itm in (string[])ViewData[‘data3’])
{ <h2> @itm </h2> } }
So we type casted here, since razor wasnt able to figure out the data type w/o it

This data becomes null if view is changed, i.e abouts view wont work in contact view

2. VIEWBAG —-
ViewBag.<PropertyName> = <Value>;
Property – string and Value – string, obj, int, list, anything …
ViewBag.data1 = “ahha”;
@ViewBag.data1

Not type casting needed in this alike in viewdata, so we dont need to mention typ of
Value while using it or accessing it, below src
Viewbag and viewdata, can be interchgned in cntr and view
I.e cntr → ViewBag.data = “ads”; view– @ViewData[“data”] will work and viceversa

Data is lost in veiwbag alike in viewdata when view changed.

3.TempData
TempData[“data”] = “accs”; → cntrl
@TempData[‘data”] → view
This data can be used only with one view, any view across webapp, i.e made in index
cntr bt used in contact view is possible, bt than it cant be used in anyother view.

To get it kept, apply TempData.Keep( empty or keys ) at end of cntr program, this way
the value will be maintained across multiple views. Session concept makes this easy.

MODELS

Repository pattern

We make an extra class where we process the data between cntr and db data
This is loosely coupling and adds abstraction layer
In repository folder make a class exgtending IStudent
Public class studRepo : IStudent {
Public List<StudentMode> getAllstd(){ return alldata() }
Public StudentModel getstdbyId( int id ) { return alldata().Where( x => x.id == id ); }
Private List< Strudmode > alldata(){ fetched from db }

In cntrl mention the repo


Private readonly StudentRepositort _stdrepo = null;
Create its obj in constructor to access its method in cntrl

PASSING DATA OF MODEL TO VIEW FROM CNTRL USING VIEWDATA N OTHR…

THEN WRITE RAZOR IN VIEW FILES

4.STRONGLY TYPED VIEW


Used to send db data usually to view, ie Model obj are sent
Ex model emp initiated in cntrl, obj is fed vals and sent to view
This obj is recvd in view liek this
@model path.emp
@*<he> @Model.empId </h2> *@

If list of obj sent to view than use this way …


view

cntr

model
TAG HELPER

ADD IN VIEWIMPORTS FILE


@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
This it can be used anywhere in asp app, line 4 is w/ tag helpers

MODEL BINDING
[Htpp Request]
Needs to be added above cntrlr action method

FORM VALIDATIONS

[Required] [StringLength] [EmailAddress] [Range] [RegularExpression]


[Compare] [Phone] [Url]

ENTITY FRAMEWORK - USED TO DB CNNECTIVITY

Step1 - all below install

TOOLS - migrations and automating Dbcntx


Design - design time logic
Step 2 - make model class

And Dbcntxt class


Dbcntrx is integral part of EF, we use in app to interafct with db, manages conn
STEP 3 - Create a Connection String in appsetings.json file
STEP 4 - Registering conn str in program.cs
Step 5 - Add migration and run migration

SESSION
Used to maintain state of vars,
STEP 1 - builder.Services.AddSession(); add this before build AND
app.UseSesson(); middleware
STEP 2 - Create session variable in cntrl
Using Microsoft.Aspnetcore.Http
HttpContext.Session.SetString(“KEY”,”value”);
STEP 3 - ACCESS SESSION VAR in actn methods by
HttpContext.Session.GetString(“KET”);

STEP 4 - To access session directly in view, use HttpContextAccessor


For this add in program.cs
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
And write this in view
DROPDOWN

BINDING MULTIPLE MODELS TO A VIEW

We can only bind one model to a view at a time, for multiple models, we put those
each models into a list, make a view which takes in list and add these lists into
that models list and than bind that model to the view and access the vals using
object operator
PARTIAL VIEWS
Its imp concept, kinda used for making SPA apps.Recom syntax of naming file is
starting name w underscore _Name.cshtml. We hv to insert it into main view to use.
Rest at shared folder. Multiple PV can be inserted in main view.
<partial name=”_Filename”/> —-> add this line in any view where u want PV to be.
TYPES 1. STATIC 2. DYNAMIC
PV WITH MODEL ( ALSO CALLED DYNAMIC PV )
We bind a model to our PV and than use that PV across diff views
THIS IS CNTRL CLASS SENDING DATA TO VIEW

THIS IS CNTRL VIEW


SAME VIEW, USING PV, SENDING THEM DATA RCVD FROM CNTRL

THIS IS PV BINDED TO MODEL PRODUCT

You might also like