0% found this document useful (0 votes)
79 views

MVC Interview

Uploaded by

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

MVC Interview

Uploaded by

prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 26
ASP.NET MVC Interview Questions MVC Interview Questions youre planing attend 2 NET Itervew, you may ah be prepared for ASPET MIC interview questions. MVCis the famework ued to build Web appliatns for NET and Cs. In this are st the op S0 MVC questions and thei answers. The aswes ae code examples writen by ators oF CH Comer 1, What is MVC (Model View Controller)? ‘Mouel-vew-conteller (MVC) i software architectural pater for implementing wer interices. It divide a piven software pplication ino three ‘interconnected pars, 20 to separte intemal representation formation from the way tht information i prevented to or acepted rom the Wer MVC isa framework for building web applications using an MVC (Model View Contos) desig: +The Mods epresente the application core for instance alist of dbase record) {The View diplas the data he database cords), 1 The Contller handles the pu (the database record). ‘The MVC mode also provides contol over HTML, CSS, and JavaScript. « ‘The MVC model defines web applications with 3 tole layers, +The business layer (Mode! logie) The disp ayer (View logic) + The inpur conta (Coazole lope) "The Model isthe part ofthe application tht handles heli forthe application dat ‘ten model objects retrieve dat (end store data) fom datbase ‘The View isthe pat ofthe aplication that handles the display ofthe data ‘Most often the views at rete fom the model dat, The Ce roller isthe part ofthe aplication tat handles user interaction ‘Typically consoles ead dat from a view, conta ser np, ad send input data othe model ‘The MVC separation helps you manage complex applications because you can focus on one aspect time, For example, you can focus on the view without depending on the busncs lope Taleo makes casero test ab aplication, The MVC separation also simplifies group development Different developers can work on he view, the controle logic nthe busines logic in parle, ‘Leam more about ASPNET MVC bere: Overview OFASPNET MVC 2. What are the advantages of MVC? Maite view support ‘De to the separation of he mode rom the view, the user interface can display multiple views ofthe same data atthe same time Change Accommodation User interfaces tnd to change more fequetl than business ules (ferent colors, fonts, seteen layouts, and levels of suppor for new devices such cll phones PDAS) because the model does aot depend on the views, ang new ies of views to the system generally does no aes the mode. Asa res the Scope of cane is confined othe view. SoC - Separation of Concerns Separation of Consors is one f th core advantages of ASP.NET MVC. The MVC framework provides coun separation of the Ul, Business Logic, Molo Data ‘More Control ‘The ASPNET MVC framework provides more entol over HTML, JavaScript, and CSS than the uadional Web Forms ASPNET MVC framework provides bet testability ofthe Web Application and good suppor for est driven develapaat oo. eight ASPNET MVC fiamework dosen't use View Stats and this reduces the handwvidih ofthe request to an extent. (One ofthe key advantages of using ASPNET MVC is that itis uit on top ofthe ASPNET framework and hence moto the features ofthe ASPNET like membership providers, ols, t ea stil be used ere is a detailed article on Creating a Simple Application Using MVC 4.0, 3. Explain MVC application life cycle? ‘Any web aplication has two main excetion tps, fst understanding he request and depending onthe type ofthe request sending out an appropiate response ‘MVC application life eye isnot diferea i has wo main phates, fist reing the equest object and second sending out response tothe Wowsct (Creating the request object, ‘The request objet cretion has four major steps. The fllowing isa detailed expla Step 1-Filoute [MIC request are mapped to ouetbles which in tum spoil which contol and action to be invoked. Soe request is the Sit russ th it hing ito ‘lhe out able with routes calletion. This iling ofthe rout able happens the global asx le Step 2 -Fetch route Depending onthe URL sent “UriRoutingModule” searches he route abet rete “RouteDas” objet which as the dtl of which controller and ation to invoke, Step 3 Request context created ‘The “RouteDuta” object is used to create the “RequestContext” object, Step 4 Controller instance ereated “This roques objects sent to“ Mvcander” instance orate the controll class nstancs, Ones the controle lt objos i rested it calle the “Exseute™ smthod ofthe contller clas, Creating a Response object ‘This phate has two steps excetng the ston and lly sending the response as resto the view: oe ae, os o ie Here complete aicle on ASPANet MVC Life Cyele 4, List out different return types of a controller action method? ‘There are total of nine rete types we can us to retu resuls fom the contol 1 view. The base type ofl these result ype is ActonRessh Viwksul (Few) ‘This rtm type is ued to ota a webpage ftom an ation method artiallewResul (Partiatview) This ret type is used o send pat of view that wil be rendre in sother view RedirectResu (Redirect) ‘This rerun ype is used to ode to any other conte nd ction method depending on the URL. RedivectToRonteResult (RedirectToAction,RediectTORout) This return type is wed when we wa oedet to any lhe ction met, ContenResut (Conte) ‘This return type is used to retum HTTP content ype like explain a the result ofthe aeton, jsonResult Goon) This return type is used when we want 9 zum JSON message fvascripmesul (avasrpt) This reun ype suse to rete JavaScript ode tht wil ra inthe browser FileResult Fe) ‘This retum type is ued to send binary ouput in reponse Emporesult This rem type sued to rete nothing (vo) in the esl ere is a complete atc on Various Retun Types From MVC Controle. 5, What are the Filters in MVC? In MVC, controllers define action methods and thse aston metnds generally have a one-f-ane relationship wih UT controls such as cickinga bution ora in, ee: For example, i ne of our previous examples the UserContoler class comained methods UserAdd, UsexDelets ‘But many times we would tke o perform some astion here a ale particular operation Fr achieving this fantionaiy, ASPNET MVC provides fenre toad pre and pstaction behaviors on the contol’ action methods. ‘Types of Filters ASPNEF MVC framework sepport the following setion ites, + Action Filters “Action ites ae sod to implement logic hat gos exccued before and air a controle action exceutes. We wil ook at Acton Filters in tai in ahs chapter. + Authoraton Filters ‘Awthorzton fer are wed to plement authentication and authorization for eomtole scons. + Rent Plters Rel fier contin Jogi hal exccued before and fcr a vcw resis exeevted, For example, you might want o modify view res right ote th view rendered to the Brows, + Exception Filters xeepton far ate the las spe of ie to run. You can ws an exception ster to handle errs raise by either you enol actions or contol action rls. You eam also use exception filers to log ers. ‘Action ites ae oe ofthe most commonly used filters to perform adiional data processing, or manipulating the return values or canceling the execution ofan io or modifying the view sete a un ine, Here is a complate ate on Understanding Firs in MVC. 6, What are Action Filters in MVC? Answer= Action Filters ‘Action Filters are alton tibate tha canbe applied o ether contllr section ot the entire conller to modi the way in which actin is exeated, ‘These ashes are pesial NLT clases derived fom System APtribste which canbe atached ta cases, methods, properties a0 feds, ASP.NET MVC provides the following action fers, + Ostput Cache ‘This action fier caches the ouput of ontoller action for aspect amsount of ine. + Handle Bror ‘This action fer handles eros raised when a contol ation executes, + duthorise ‘This ation fier enables yout estict accesso a patcalar sero rle ‘Now we will ce the code example apply these ites on an example contller ActionFitesDemoContoll (ActonFierDemoContolle is just used a an ‘example. You can ase thee ters on any of your conlles ‘ouput Cache Code Example Specifics the return value to be cached for 10 seconds. e Loeepcet) Sreseecane(ouratton = 209) pubise sing inset) t > > oe Leam more here: ASPNET MVC with Action Filles 7. Explain what is routing in MVC? What are the three segments for routing important? Routing is a mechanism to process the incoming URL tat is more descriptive and gives he desired response. In this case, URL isnot mapped to spesifc ies or folds wa the cas of eae days wo ates, ‘There are two types of routing (afer the intoduction of ASPNET MVC 5), 1. Conventon-bsed routing to define this typeof routing, we eal MapRoute method and sts unigue name, URL pater and specify some default vals 2. Atribue-based routing fo define tis typeof routing, we specify the Route atte inthe action method ofthe contre, ‘Routing isthe URL pattern that is mapped toeter to hale outing is responsible fo incoming browser request for particular MVC contol. In ater ways Jets 8 routing help you lo defines URL sacar and map the URL with conglle. here are thre segments for routing tht ae important, 1. ConteliseName 2 ActonMthogName 5 Parameter Code Example (ContleNameActionMethodName/{ParamerName) and also route map coding writen in a Global asx ie ‘Leam more bere - Routing ia MVC. 8. What is Route in MVC? What is Default Route in MVC? ‘A route is URL patter that mapped oa handler. The hander canbe a physical file suchas aspx fle ina Web Forms aplication. A handler can also be a las tht processes the request, such asa contol in an MVC application To define a rout, you creat an astaace of the Rois cas by specitying te URL paler the handle, an optionally name (or he route, ‘You add the route othe application by adding the Route objeto the state Routes propery ofthe RouteTable eas. Th Routespeopety isa RowsCollestion bjt that stores all the routes for he application ‘You typically do not ave to write code oad routes in an MVC spicas are defied inthe MVC Applicaton clas, which defined inthe Globalasax fle Route defn Example of matehing URL {controller fection) fd} ‘rodctnshow beverages {table Detalsagpx Product Deas agp bog action} {entry} ‘log'show/123 {rspontype}/(yea|/fmorah}fday) | sales 2008//5| locale} faction} USishow language}-fcountytaction} | ea-USshow Default Route The default ASPNET MVC project templates ad a genetic route that wes thefllowing URL convention to break the URL forgiven regust nt thre named segment. URL: "{conole}/(acton} i) lesion, This route patter srpistred via a cll tothe MapRoue) extension method of Route public static vold Registerfoutes(ToiteCollection routes) { routes. IgnoneRoute(”{resource).axa/(*patntnta}"); recas.tntvt( gure ond ith cd tesin seer, thane Tir (telly tctiny tg, — URL Pa te Cee ecm aa bs 9. Mention what the difference between Temp data, View, and View Bag? NEP MVC there ae tree ways to passsore data between the contollers and views, ViewData 1. ViewData is used to pass data fom comtole to view. 2 Its derived from ViewDataDictonary class 5 tis eval for th current request nly 4. Requires typecasting for complex data ypes and check for nll value to avoid an enor. 5 Ievedirecton occur, then value Becomes nl. Viewtiag 1. ViewBug is also use to pass data fom the contolle to he respective view 2. View Bag is a dynamic property that takes advantage of the new dynamic feats in C#40 5 Inisato avalible or he caret request nly 4 Ifreireton eco, the swale Docomes all. 5 It oes equietypecasting forthe comple datatype TempData 1. TempData ie derive fom TempDatsDictonay clase 2 TempData is sed fo pase daa from the cuten request tothe next reqs 53. Itkeeps the information forthe time of a ITT Request This means only fom one page to another, It lps orsitsn the dla when we move fom one conrallerownotherconrller a ftom ane action to another ation 4. Itrogirestypecasting for complex datatypes and shosks fr tll vale o avoid an er, Generally itis used to toe only onetime messages like Lea more ber: Difecace Batwosn ViewDita, ViewDag, and TempData 10. What is Partial View in MVC? 2. Vsual Studio projet emplates for MVC include preconfigured URE routes. These ‘A pata view is @ chunk of HTML that can be safely inserted into an exiting DOM. Most commonly, partial vows ae used to componcntize Razor views and ‘ake them sate to ui ad update, Pail views ea als be rtured diel Sram concoller metho In thi cae, the browser sil ects exhi ‘content bur nt necesuily HTML coateat that makes up an cate page. AS a esl, fa URL that tars a paral view is dec invoked from the ares bar (ofa browse, an incomplete page maybe displayed. This maybe something like a pags that mises il, sept and style shects. However, whee the same URE is Jnvoked via seri, and the response sued to inset HTML within the existing DOM, tenth nt effet forthe end-use may e much eter and lee Paria view isa reusable view (ike a wer contol) whic can be embeded inside another view. Fr example, let's say ll the pages of yours havea sandand strgtue With left menu, Reade, and ote asi the folowing image, HEADER Dynamic goes here FOOTER 2 ettn Let's make this as mece of code reusable ‘Lea more bore - Paral View in MVC 11. Explain what is the difference between View and Partial View? View + Itcontias the yout pe, + Before any view is rndered,viewstart page is rence ‘A view might have markup fags like body, HTML, ead il, meta ee. 1 The view not liphtcight a compare Lo Paral View Parts + It doesnot conan the layout page + Partial vow doesnot very fora viewsareshml. We cannot put common eode for a paral view within the viewStar est page 1 aril wow is designed specially o reader within the vew an jt Beene of hati Goes no consi ty mk 9, + Weean passe regular view tothe Rende-Prial metiod LLeam more bor - Paral View in MVC 12. What are HTML helpers in MVC? ‘With MVC, HTML helpers are much ike traditional ASPNET Web Form contol. Sst ike web form controls in ASPNET, HTML helpers are used to modify HTML. But HIME helpers are more lightweight, Unlike Web Form controls an FTTML helper doesnot have as event model and a view st ‘In mos cases, an HTML helper is just a method tha retusa string. ‘With MVC, you can create your own helpers, aus the bul in HTME helpers landara HMI Helpers HTML Links “The easiest way to render an HTML linkin to use the HTML. Action ink) helper With MVC the Html Aston ink) does no ink to view: I rete ink to contoller action. ASP Syntax ‘eomtalsAtienLink(About this Website”, "Abst" ASPNET CH) ‘The ist parameters the link text, and the second parameter isthe name oF the contol eton The Himl ActionLink) helper above, outputs the following HTML: Mashup ‘The Hem Actonink() elper has several properties: + Property Deseriton. link Tex The ink eta. actiouName The age tion routeValues The values pated to the ction onolleName Tae get controle hmlAtbates The sto tbat to he ink prococal The link protocol hostname The host name fr the link ffagment The anchor target forte lnk {ITM Form Elements hee following IITML helpers canbe used to render (modi nd ouput) ITTML farm elements + BegiaForm) EndFormg 2 Tenarea) + TexBoxd + Chesktox0) RadioButton) 2 Linoxd + DropDowaList 1 Hidden) aso ASPNET syntax C# Ge Wen valldatlonsumary(“create wae unsuccessful. Please correct the errars and try agtn.") 2 uring ta bogarorn( 9 label fnw"Firsthae"sFirst Maese/Iabel> Ge ttl rostbonterirataare") 3 (ied fdntiomossage(estAane cy ips label frw'Lartae'stast Nats el TextboxCtasthane”) ‘Gr te vatlantiowessage("Lastane”, "4) 2 “ip Ge el sPassuord( Password") ead vaientionmessage Password", "*) 2 swcrs"scantien Passords ix al paceuned( contiownreusde) (i vat Teatiowessage(“conrrapusswond", °*°) 8 ip aspen forsee Proftlese/atel> gpd wate ti ee (ehesh, cet > “Hel cneconRacebveewsetger") {bb arssnscedveknslotter™ style-"dlaplaycinlsne"»eceive Newletter ip abate" value-tnegister"/> Be ASPNET (CH) ‘Lean more her ITM Helpers in MVC: Pa 13. Explain attribute based routing in MVC? In ASPNET MVC 50 we havea new abate routecBy using the “Route” athe we can define the URL structure. For example the below code we have oe Lear more here Atribute Based Routing sm ASPNet MVC S 14, What is TempData in MVC? Temata dictionary object to store data temporal Is» TempDataDictonary clas type and instance property of the Cooler base cas ‘TempData sabe to keep data fr th dation of «HTP request, in other words it ean kep live dita between two consecutive HTTP requests, will slp us to pas the slate Between action methods. TempDa only works wi the curren and subsequent reques TempData uses esi variable lo soe the data TempData Requires type casting when sed to retneve data TempDataDitonay i inherited from the IDctionarystring,abeee>,IClleton, lEnumerablecKey aluePartring, object and IEnumerable interfaces Example fublse aciontesuit FiestReques() t ist ¢ srdng > tenpatatest = now ist < sting > Or Senponeaost tealsTesae")} ‘enponatestadat-Jegesy®); ‘Seropatatest aed(-taese") Tersbatal"Engane”) = TengoataTest Feturn Views > uote Actiontesurt Consecutiveequest() ¢ List < string > nodelbata » Tenpoatal"Eeptone] a5 List ¢ string > 5 erste. ceoh Petaen Viewteon oat) > or ‘Leam ene betel About the TempDaa in MVC 15, What is Razor in MVC? ASP.NET MVC has alway soported he concep of “view engines” - which ar he plggable modules that implement differen template syn options, The "defulvow cage for ASPNET MVC uses the samc asp aren maser ile emplates as ASP.NET Web Forme. Other popular ASP.NET MV view gins ate Spares ‘MVC has introduced a new view engine called Razor. Why is Razor? 1. Compact & Fxpressiv. 2 Razor minimizes the numberof characters and Keystrokes reuied in file, and enables a fas coding workflow. Unlike most template syntaes, you. donot nce nterapt your coding to explicly denote server blocks within your IITML. The parsers smart enough to ner hit fom your ede ‘This enables really compact and expensive sytan wih clean, fata fant 9B, 3. Baty to Lean: Razors casy toler and enables you to quickly be productive witha minimum of effort, We can use. WTML sills 4. Works with ny Tent ator: Razor dosnt aque a specific tol and enables you to he productive in any plain od ext eit (notepad works gest) 5 Has great Inelsense: 6 Unis Tesuble: The new vow engine implementation wll suppor the ability to unittest vows (without equting a conuoller or web-sever and ean ‘be hosted in any unit st project - no special app-doman gute). your existing language and Lea more ber - Brief introduction to MVC3 16. Differences between Razor and ASPX View Engine in MVC? Razor View Engine VS ASPX. ASPX View Engine (Web form view engine) The namespace used by the Razor View Engine is System.Web Razor The namespace used by the ASPX View Engines ‘System, Wea Mve. WebFornViewngne ‘The file exeusions used by the Razor View Engine ae difeceat Shor web frm view engine Ieuss eshiml with C# and vb ‘th vb fr views, partial view, emplies and layout pages, The file extensions used by she Web Form View Engines te ike ASPNet web orm Luss the ASPX extension to vow the spe extension for partial views at User Contols or templates and maser exensions fr lyoutimaste pages, The Razor View Engin isan advanced vw cngin that was sntoduced with MVC 30, This is aot anew language batts ‘markup. [Awe form view engines the dfiult view engine and availabe from the beginning ofMve ‘Razor has sya that is very compact and helps us to ede he web form view engin has sya has the same akan ASP.Net forms npicaton The Razor View Engine uses @ 1 ender serveside content, The ASPX/we form view engine uses "6-65" on "<2" a render serverside ‘By defalall text fom an @ expresion is HTML encoded ‘Trea iffrent syntax ("4:92") to make text HTML encoded, Razor dock not require the codeblock to be else the Razor View [Engine pares ive eit abl to decide at runtime whichis 8 ‘content element ad which code element ‘A web form view eine rues the codeblock tobe elsed propely other it throws a rite exception, The Razor View Engine prventsCrss-Site Septing (XSS) attacks by encoding the script o HTML tags before rendering othe view. A.web frm View engine doesnt prevent CossSiteSerping(XSS) attacks The Razor nin sports Test Driven Development (TDD) Web Form view engine doesnot suppor Test Driven Development (TDD) because it pends on the System Web UI Page els to make the esting complex Razor uses "@* He“ for multiline commen ‘The ASPX View Engine use "<>" for markup and" €or Cs code, ‘aera only tne wanton characters withthe Razor View Engine ‘Tere are only toe transition characters withthe Razor View Engine. The Razor View Engine is it slower than the ASPX View Engine. Conclusion Razor provides 4 new view engine with a sueaiined code for focused templating. Rec’ satan very compact ad improves the redability ofthe ack and coe. By defiul, MVC supports ASPX (web forms) and Razor View Engine MVC also suppors ‘ShaspDOM and so on, ASPNET MVC is open route, ‘Lear more here - ASPX View Engine VS Razor View Engine 17, What are the Main Razor Syntax Rules? + Razor code blocks are enloed in @{ 4 Inline expressions (variables and functions stant with @ {Code statements end with semicolon 5 Vibes are declared withthe var Keyword {Stings ere coclnrd with quotation murs 1 Gtende is cae sensitive 1 Gp les have the extension tal ee varnytesage = bie ami ab velo yestage it esses « > rept view engines lke Spark, Naz, Nang, argrectingtessage = gesting + * Hare in ston St Sst * + weekDoys 2g pone grecting i Epreetghessope c /3 oe ‘Lea more ber - triton lo Micrxall ASPET MVC 3 Ravor View Engine 18, How do you implement Forms authentication in MVC? Answer ‘Authentication is giving acess othe ser for a specific service by verifying hier identity using ister credentials like usemame and password or email and password It atsures thatthe coect users autheticated of logged i fo a specific service andthe ight service hasbeen provided to the specific ser based ot ‘heirole ha is othing but authorization, [ASPNET forms authentication occurs af IS authentication is completed. You ea configu forms autbenscation by using forms clement with ia web contig fileof your aplication The defasl atribule values for forme aeration are shown how, csyetena cfoystennes>| Morkop ‘The FormsAutentcation lass eeaes the authentication cookie automatically when SerAuthCookie) or RedieetFomLoginPagel) methods are called. The sale of authentication eaoke conan sting representation ofthe enerypled snd signed FormsAutbentctionTicket object Learn more hee» Form Authentication in MVC Sar 19, Explain Areas in MVC? newer rom ASPNet MVC 2.0 Micosoft provide anew feature in MVC applications, Arcs. Area re jus way to divide or “isolate the moles of arge pplications in multiple or separated MVC. lke, ‘When you ad an area to a project, route forte ata is find in an AveaRepstaton fle. The route sends requests othe are basod on the request URL. To register route foe aes, you add eod to theGlbal asx Sle hat can automatically fn the area routes in the AveaRegistation Se AveaRegitration RgisterAléreas, Benefit of Area in MVC 1. Allows us to organize modes views and contoles nt separate functional sttions ofthe application sich as administration, ing customer support and much more 2. Baty to integrate wih oir Areas created by another 5 Fasy for unit testing ‘Leen more ete - What Azo Aras in ASPNet MVC Pat 6 20. Explain the need of display mode in MVC? Anewer DisplayModes give you another level ffeil on op ofthe del capabilites we saw in the lst section, DisplayModes an also be used alongwith the previous Fate so we wil simply bull off ofthe ste we just crested Using display modes involves in 2 steps 1. We shuld register Display Mode wit sufi for particu Global asx fle 2. View same for particular browse shouldbe appended with suffix mentioned in fist step, browser using “DefaltDisplayMode"e cls inApplication Stat method inthe heslatoser ei: Gate ee bar Deron atsoarones(0) ot Syetan uso eahogoe DerauieDLcplaphed]+ (Syeten. Web onagee.Dofast®DL=paytate) {Sistev. eo ior apes eral Ospayrece) i Sis eaten: tenses ne ratte 1. Desktop browses (vihout any sfx «Index shim, Layout shin) 2. Mohie browser (with ufix "Mobile™ eg: Index Mobile sim Layout Mobile cstm) Ifyou want design diferent pages fr differen mobile device nowscrs any diferea nowsers) and ender them depending on the browser eustng To handle these requests you can register custom display modes. We can do that using Display ModeProviderTnstance Modes Iaserint index, [DisplayMode iter) method, ‘Lear more here - Display Mode Provide in MVC § Application 21. Explain the concept of MVC Scaffolding? Answer ASPNET Sealing isa code generation fiamework for ASPNET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and ‘Wed API projects. You ad seaffolding to your projet when you want 19 icky a code that interac with data rdel Using sealing ean reduce the amount of time te develop standard data operations in your project. Scaffolding consists of page templates, entity page templates, Held page templates, and fier templates. These templates are called Scaffold templates and allow you to quickly build a funcional dae-drven Website. SS SSEer ese! Scaffolding Templates Create Iirsates a View that helps in cesing anew rocord forthe Model. It automatically generates abe and inp eld for each propery he Model Delete ‘Weveates ist of eco rom the model callection along with th delete ink with delete record Detaits 1 gencatesa view that displays the label and an input field ofthe each property ofthe Model inthe MVC framework. ait ‘Weveates a View with form that helps inciting the euent Model It ls generates a form with lube and el for cach propery ofthe model List 11 gency crests a View with he help of ITM tbl hat ists the Models rcs the Model Colleton. It alo genertes IML table coum foreach propery of tae ModeL ‘Lear more here- Terminologies in MVC: Part (Scaffolding) 22. What is Route Constraints in MVC? Answer ‘Routing isa great feature of MVC, it provides a REST based URL thats very easy to remember and improves page ranking in search engines This ale snot an introdtion to Routing n MIVC, but we wil earn few fetures of routing and by implementing them we en develop very lexible and sucriendy spplicnson, Soles start without wasting valanble ime Add constrain to URL, ‘This is very necessary for when we ant to add a specific consent to our URL. Say, for example we want a URL. So, we want set some constant sting afer ou host name. Fie, les see howto implement i 1 very simple implement just open the RouteConfigs file and you wil ing the routing definition in that. And modify the routing entry ain the following ‘We wl se that we have edded “abe” befor. “ 2S af [1 tocamnost2268/abepe200 am inl ‘Leam more here Route Constins ia MVC 23. What is Razor View Engine in MVC? ASPNE MVC has always suported the concep of vow engines” tat are the pluggable modules hat implemen! various template sya options The "defeat view engine for ASPNET MV uses the same asp asov!mase ile templates as ASPNET Wel Forms. nti rice I go trough the Razor View Engine to creat a view of an application. "Razor" wasn development begining in June 2010 and was released for Microsoft Visual Studio January 201 Razor is nota new programming language elf but ues Ci syntax for embedding code na page without the ASPET delimiters: <> 9. Iisa imple ‘ymax iow engine and wes rleasd as pat of ASPNET MVC 5. Th Rago ile extension i “xb” forthe Cs guage. supports TDD (Test Driven Development) beense it doesnot depend onthe System. Web-UL.Page clas. ‘Lear more here Getting Started with Razor View Engine in MVC 3 24, What is Output Caching in MVC? Answer ‘The main pupose of using Output Caching ito dramatically improve the performance ofan ASP.NET MVC Applic, It enabler us to cache the content etured by any contller method s hat the sre content does not ned phe generated cach ie the sie controller method is avoked, Outpu Caching has huge advantages, soc as it reduces server round tips, educes database server round tps, reduces network afi el Keep the folowing in ming, + Avoid caching contents ha are wigue per wer 4 Avoid caching contents that are aecessed carly + Use caching for contents that are acessed fequea'y Lets take an example, My MVC appiction displays alist of database records onthe view page so by default each tine the use invokes the contol method to see record, the application loop trough te entire proces and executes the dlabate query. Ad hi can actully dccreae the appiaon performance, So, ‘ve ean advantage of he “Output Caching” that avoids exceutog database queries cach time the we invokes te controller metho. Hee the WoW page is ‘eueved ffom te cathe instead of mvoking th conwoller method and doing redundant work Cached Content Locations Inthe above paragraph sid in Output Caching the view page it rexeve from the cache, so where the eonlent cache sored? Pease not, there is guarantee tht content wil be asbod forthe amount of time tat we specify, When memory resources become lo, he cache sa veting content automaticaly ‘OuipusCache label has "Location stibute and it fll controls, Its fa value is "Aay", however hee ae the following locations avalable sof 1 Any 2 Clem, 5S Downstream Server 5. None 6 ServecAndClint ‘With “Any, he outpt cache is sored on the server where the eguet was processed. The ecommended store cachet always onthe server very cco, You ‘wll lear about some security related tps nthe folowing "Don't use Output Cache ‘Lean more here - Outpt Caching in MVC 25, What is Bundling and Minification in MVC? Answer Bundling and minfication arc two new echniqucs ntact improve request loadtime, It improves load me hy reding the numberof equ tothe server and reducing the sizeof rquesiod assets (suchas CSS and JavaScrp) Bundling Itlete us combine mukipleJavaSerit (ils or mukiple cascading syle sheet (ss) les so that hey canbe downloaded asa uni aber han maki indivi! HTTP regu, Minitication squeezes out whitespace and performs os ype of sommpreesion to make te downloade files as eral as possible, At suatime, the poost dette the ‘se gent, fr example IE, Mozilla ct and then removes whatever i speifcto Mola whet the requet coms fom IE. ‘Lea more here - Bundling and Miniiation in Visual Studio 2012 or Migrate Existing Website 26. What is Validation Summary in MVC? Answer "The ValdationSurmary helper method generate an unordered ist (element) of vaidation messages that ae in the ModelStteDitionsry objec. ‘The ValdationSummary canbe sod te display all heer messages for al the feds, Iscan lg be used o display custom eror messages. The following figure shows how ValdaonSunumaty displays the cor messages, Edit ‘Student + The Name fed is required + The Age fed i required Name Age swe ‘ValidationSummary0 Signature MocHonlsiringValdateMesage(bo0 exludePropertyBvrors, string mestage, object RiAtributs) Display eld Level errr messages using ValidationSummary ‘By dofaul, VlidationSunmmary irs ou fold level eor messages. Ifyou wan to display fl lve err messages asa summary thon speety cexchdePropertErars = false, Example- ValidationSummary to display Held errors Hm FaidaionSunmary alse, "new { @elass = ecdanger”}) So now the following Ei view wil display eror messages summary at the tap, Please make sre tha you dont have a VaidtionMessaeFor method for cach ofthe Geld, Edit ‘Student ‘Lea more here - Understanding Validation Ia MVC- Past 4 27, What is Database First Approach in MVC using Entity Framewor! Ansner Database First Approach san alternative to the Code First and Mode Ft proaches othe Entity Data Model which creates model codes (asses properties, DoContextcs) fom the database the project and that lasses beaves asthe link between araase and controler. ‘Thera the following approach whichis used connect with dataset aplication, “Database Fit Model Firs 1 Cade Fit Database First Existing presiel Preyer Database firsts nothing but only approach to crete web application where database is valale fist and can interact wth the database. In his database, database created frst and afte that we manage the code: The Tatty Framework i able o generate a business model based onthe table art columns in relional tas, ‘Lean more hate - Dutbase First Approach With ASPNET MVC Step By Step Pat 1 28, What are the Folders in MVC application solutions? Ansner- Understanding the folders ‘When you crest projec folder race gts crete by default under the name of your projet which can he seen in soliton explorer, Below wil give you brief explanation of wha hese folders re for. Model ‘This folder contains classes thats used to provide data These classes can contin data that i etrived fom the database or data inserted in the fem by the user, to update the database, Controllers ‘Thos re he classes which wil perform the action invoked bythe user. Tese classes contains methods known as “Actions which responds to the usr action secordingly Views ‘Those te simple pages which uses the model class data to populate th App Start ITML conto a enders ito the cic browser. (Contin Clases sch 8 FllerContg, RoutesConfig, WebApiConfig, Ax of now we aed to understand the RotteConfig class, Tis clas contin the def format ofthe url tht should be supplied inthe browser to navigate wa specified pase 29. What is difference between MVC and Web Forms? SP.Net MVC! Web Forms Anawer= terenee ‘The following are some ditfreee. ASP.Net MVE ASP.Net Web Forms ‘View and lope are separate, it as separation of concems theory. MVC 3 onwards as| aspx page sesh "No separation of concerns; Viewsat tightly coupled with logie Caspees file. Inoood concept of rong for route based URL. Routing i devlred in Global asa for cxample. Filehated routing. Reetion is based om pes ‘Support Razor syntax as wells .aspx Support web forms eytax only. State management handled vie Tempdata, ViewBag, and View Data Sinee the eonller, td view ee nol dependent and also sice there bs no view state concept in ASPNET, MVC keeps the pages ihtweight ‘tate management hadled via View State, Large views, in cer words increase in page sz. Paral Views rer Contras HTML Helpers Server Contos Mulple pages can hve the same controller to sty their requirements. A controller may have miliple Actions (method ram inside the controller ls. ach pe hai own code in oher words direct dependency on ode, For example Sachin as ie dependent on Sachin.agp.cs (code being) le ‘Unit Testing is quite easier than ASPNet Web forms Since a webform and code are separate ils. Diret dependency, tight coupling raises issues in etn. Iayouts ere are more Similars and Dissimilanies Between MVC and Web Forms 30. What are the methods of handling an Error in MVC? Answer Except handling may be required in any application, whether itis eh appicton ora Windows Forms application ASPNeL MVC has a tribute called “HandleEeor that provides bli exception Sites. The HandleEeor atibute in ASP.NET MVC can be applied over ‘he action method aswell x Controller ra the global level The ilandletor atu she dels implementation of IExceptionPiler. When we erate MIC application, the HandeEoratibute is add within the Global asan.es file and registered in the Application, Sart ever, public static vold egisterGlovlFiIeers(ahobelrsltercollection #lter) ‘tates datnen HandetrvorAtetbutet)}s > Brotectegwotd application start() t srcategistrat ion tegveralare() episcerlonnifsiters(ciobain ere Registestovtes(eoutelosie-tovts); > be Important properties of Handle rrr attribute The Handler Ero atsibute has «coupe for properties ha ae very useful in handling the exception ExceptionType ‘Type of exception tobe catch. I this propery isnt specified then the HandleEor iter handles all exceptions ‘Name ofthe view page fr dspayng the exception information Master “Master View for displaying the exception Order ‘Osdrin which the ation Sites are exeuted. The Order propery hasan integer valve adit spelfies the privy from Ito any postive integer value. | means highest priya the grater the value of the integer ig the lowers the prio ofthe ier. Allow Matte indicts wheter more than one instance of the cor fie tbe canbe specified Example [Bonetetrrer(vtew = “ervor*) c public Actonkesult Iodex() [Cts Convert Tomnts20e")p 1) error Zine” ature eat); > > be andesorAuribute at Action Method Level, [eanetegrvon(view = “Error puctse acionsest2e lex) (aes message + welcone £0 59.NEF mC TUE Gwart felmee")3 /) ear Sine return vent); > on ‘ere are more detail on Exception or Fer Handing it ASPNet MVC Using Handlerae Abus 31, How can we pass the data From Controller To View In MVC? Answer “Ther ae thee options n Model View Controller (MVC) for passing data from cone to wew: This ariel temps to explain the diferences among ‘ViewData, Viewbag and TerspData with examples. ViewData and ViewBag ae similar and TempData performs adational espansility. The following ar the ey points on those tee objets, ViewDats +The ViewDanais sod to move data from contllero view. 1 The ViewData ia dictionary of objects tha are derived ftom the "ViewDataDictonay” class and it wll be accesible using stings a keys + ViewData consis a nll vale when erection secu ‘+ ViewDaca reguiresypecating for complex datatypes. Venta + ViewBagis just a dynamic wrapper arund ViewData and exists only in ASPNET MVC. ViewBag.is dynamic property tha takes advantage of she new dynamic Features in C40. + ViewBay desi equieypecasing for complex data yp * View ay also conan a null value when edteton occu ‘TempData + ViewData moves data fom como to view: + Use TempData when you need data tobe available fo the nox request, only the next questi wil be thee but wil be gone afr tat + TempData i od to pss data from the cure requst othe subseghsn equct, i ther words ease of erection. Tha means the value of ‘TempData will ot be ll Lea more her - Virus Way o Pass Data From Contoller to View in MVC 4 32. What is Scaffolding in MVC? Answer ‘Scaffolding isa code generation framework for ASPNET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web APL projects, You add seffolding to your project when you want quickly ad code that neracs with data models, Using weafolding cat reduce the amoust of {ine to develop standard data operation in your projet Prerequisites ‘Tose ASPNET Scaffolding, you must ave, + Microsoft Visual Studio 2013 1 Woh Developer Tools (pat of dfast Visual Studio 2013 insalation) ‘+ ASPNET Web Frameworks and Tools 2013 (par of default Visual Stadio 2013 installation) wat the Advantages of using Scaffolding ? Minimal or ne code to crete a data-driven We applications 5 Quick development time {Pages tha ae fll functional and include display inserted, delet, sorting and paging functionals. 1 Bulein dus validation thats based onthe databace sche, 1 Filters that ae erated foreach foreign key o Boolean Hels. ‘Lea more bere -Seafoding a MVC S 33. What is ViewStart? Answer ‘Razor View Engin intodaced anew layout named _ViewStrt which saplid on all view automatically Razor View Engine Sistly executes the ViewStar nthe start rendering he other view and merges tem, Layout = *-/vseus/saret/_vteshtnt”; d E isocrye tent » content slldenedeearuiden” / > epee < pels Markup ‘Lean more here Viewsat Page in ASPNET MVC 34. What is JsonResultType in MVC? Answer ‘Action methods on conrlies return Jones JavaScript Object Notation result tht canbe used in an AFAX application. This ls is inherited fom the "ActionResult abstract class, Here Ion is provided one argument which mus be serializable. The ISON result object that serlizes the specified objec to ISON format, publse Jonsooule Jentosulevest() e retura on("Hette My Frsen > oe ‘Lear more here ActionResult Return Type in MVC 3.0 35. What is TempData’ Answer Tempdata + TempDat it ditonary object derived fom the TempDataDicionary clas. 5 TempData i sod to pase data ftom the cue request oa subsequent request, n other word inthe case of eitecton, {Tho life ofeTempData is very short and it retains vale fora shor period of tie, 1 Itreqirestypecastig foe complex dta ype at ve usd in my example + Grech iar em in (List=MVCSample Models LinpRegistation”)TerpData“EmployeeRepistation"}) {Yow ean retain ir value using the Keep method for sabeeguent rogues Liege rity ina tomes mean) Intros tpepsttn! [tse edes Een {hncsnpe es pega vesoledes pets 36. How to use ViewBag? Anener ‘ViewBag i Uynane propery that takes advantage of new dynamic features a C40. Its also used ops data fom a contoller ta view. In shor, The ‘Viewing property x snply a rapper around the ViewData that expos the ViewDats dictionary as dynamic object. Now een action tho *StudemSummay" inthe “DsplyDataContole” controller that ores Student clase object n View, public Aclontesu2tStageresumeryt) ‘ var student = new Stunt) t ee » eau. student + stents fetina view > ce ‘Thereater creat a view Studen'Summary ("StudentSummary chm) that shows student object data. VewBeg docs not equ ypecasing for complex data ‘ype so you can ditcdy access the data om View Ba. ec d S23 wane sts <0 9 Hee sey e/a «ft ete > peat Bitte Ca eee CC ede. chty <1 oe Here we use one mor ching, "View Bag Tite" tht shows the ile of he page, Learn more here - Displaying Data on View From Controller 37. What are the Difference between ViewBag& ViewData? Answer Difference between ViewBaga&ViewDats? + ViewData is dictionary of objects that it derived fom ViewDataDictonary class and accesible using sings as keys 1 View Bags dynamic property that takes advantage ofthe new dynamic fears in CH 4.0, 1 ViewDiata quires yperesting for complex data type and ches for ul vals to void ero. 1 ViewBag docs equitespocasing Tor complex data pe 1 Calling of Viewag ViewBag Name ~ "Yogesh: Calling of ewDatais RewData Name "yogesh _Learn more here-DillesocsBebwsen Viewiyg & ViewData an MVC 38. What is Data Annotation Validator Attributes in MVC? Answer Using the Data Annotation Validator Attributes DataAnaotation pays vita oe in added validation to properties while designing the model its This validation canbe added for both the elie side andthe server side ‘You understand that decorsting the properties in «mode with an Atbute can make that propery sible for Validation. Some ofthe DataAnnotation wed for validation ae given below, ort: ‘+ Mama hare nd mania ca 10 1 Range shld be between 108 a eft cick 1. Required ‘Specity property as required [Required(BnorMessas 2 RegularExpression Specifics te regular expression to validate the vale ofthe property. [Regulerxprestion([o2), Har Message= "valid character], 3. Range ‘Speci the Range of vas between which the propety vals ae checked [Range(1000, 10000 rorMessage-"Range should be beeen Tk & 10K") 4 SiringLength ‘Speciin the Min & Mas length for esting proper (StringLenghiS0, MinimumLengih~ 5, rorMessae 5. Mastength ‘Specitis the Max length fr the property value [MaxL engi O,rarMessage-"Customer Code is exceeding] 6.Minuength iis ured o chock for minimum lngth, [MiaLengths, EnorMessage = "Customer Code is too sal") *CustomesName is mandatory") Minimum char Sand maxim char ‘Leam more her - Ang Custom Validation in MVC 39. How can we done Custom Error Page in MVC? “The Handi Atibte allows you to wee «custom page for ‘his err. Fist you need to update your web config leo allow your aplication to ade fsystense®>| Marken ‘Then, your action method aceds to be matked wit the altbute [Hanetetreor) ¢ IHansaetreon) lb cet lorteceltthrowtnception) c ‘ron pe tppiicationtxception( > > be iy calling the ThrowExcepton action, this would then rediec the wer tothe deft err page nour case though, We Want oie a custom error page and rediost the user tee instead So, lets create our new eustom View page “8 Pose Lansuage-tcW" Tener inestsyaron. ob lc. PiesPase™ $8 -C/DOCTHPE hem POELIC *-//W)/ARD MRT. 1.0-Teaneitioonl/ EN" Miki a ee | ie Bie tceanesereortato|riewbara.rodat) ct sonone: 5S ve ttn tenes eee) tnspton ese BE i tonatiedcoctaso|viewDotatodel) zecestion Sackteace §F ine Bret ‘Next, we simply ned to update the HandeEsrorAtbute onthe action method. Dhendieterer) [Maneiecrear(tew « “Custentororvter")] piblschetientorsleTaaeaceptiont) t ‘rou pow sppiicatiotxception(): > > cr LLeam more here - Casto or Page in ASENET MVE 40. Server Side Validation in MVC? Answer ‘The ASP.NET MVC Framework validates any dita passe othe conole action that i executing, I popultes a Modelate object wit any validation fuse ‘hat it nds and passes that object tothe contoller. Then the conoller ations can query the ModsStte to discover whether the request valid and tea accordingly 1 wl use two approaches i this article to validate & move ta, One sto manually ad a error to the ModelSiate object and another wes the Data Anotation APLio validate the model data Approach 1 -Manually Add Error to Medel object, 1 create a User elas unde the Models folder. The User clas has two properties "Name" and "Emil", The "Name" fed has required field validations while the "Email eld has Email validation So let see the pocedre to iplement the vation. Creat the User Mode! inte following, ranergace Sarvenalidstion.ocnit t pic stn tne es > bite seeing Ematt ‘ , ? > be ‘Alle tht Irate controle action in User Contoler (UserControl es under Controllers fda) That action method bas logic forthe required validation for ‘Name and Email validtion on the Ema field. add an eror message op ModelState with key and that message willbe shown onthe view whenever the data. ‘snot be validate in the mode public clase Userconrolters controler public Actiontesut ardent) t return ext): > Uneepoost public AcLiontesult nden(Servervaiieation edele.User node!) t 16 (sting. ens Lornpty eae. Na98)) t wotelstate.aderodelEeror(Mane", "ane Se require"); i fe seine aouaototy(nde tat) string eatstenen = @ “M(2-24-20-8 \-\ J09@CCUL8-91C37 + er\Leeateayyacoess(isji.)|Tcazmzesieyc es Soviaarig,alieslaapnine: Aegon res row Raes(enasinege)? fF (lee anstenlnese erst) rodelstate AderocelEcrr("Enatt", "eat ts not valle); f pete oselstate Aerodelecror("easi", “email se rere"): ) Je comastte too f Fee Merete: > > be Thera reat a view (nde. for the usc apt unde the User fl. fel Serverveligtlon Modeler Fawn. tiete = “tnd : * festngtiemsopinroat)) 26 (Guieoata todelstate.t0valid) ¢ 56 (Guteoag.tane sat) cee one: @ieabag.nave
ra: “iviouasgensl © Jb 2 ) < Hendset > Segond 3 user ¢ legend) ¢ ay clase = Yostor-lapel” > rat Laperron(aces > del ane) ¢ /si0> ¢ sv class = "editontiele™ > [Beat Edttortor(nodet > noaei "None sie Wiesata.sogeistete. 3118) “faeldwalédetioneoror” > @viewoats toclstore( Nore"). €orors[).Errontersage /2pon> > 2 yasys «atv elses = sestarsisbel® (giat Label acomcen =) edel tna) (lwo ¢ dl class © “estor-tiene” > (Brat tdttoror(noset > nogei-tra) ‘ese(Iviewata.sngslseate. 3190) span eines = "seldevaltdation-eoror* » @uiowts.soaelstsce"Enatl"] Erona[@]-Eenanessage € /3r3 ; ret eo > vanue ="ereate™ 7» " Jps C ietetaress > JavaScript 41. What is the use of remote validation in MVC? Answer Remote validation it he proces whe we validate speife data posting data to server without posting the etie frm dato the server Let se an atl scenario, in one of my projects Thad a rquiement to validate an email ares, wheter it already exit inthe database. Remete validation Was wsefl for tha; ‘wiheur posting ll the data we can validate only the cml adatess supplied bythe use. Practical Explanation Lets rele « MVC project and name it acordinely, forme is “TestingRemotsValdation” Once the projec is created lets crete «made named UseeModel ‘hat wl ok ike: c Lteauire) c > {tonte(checklatngingl, ore", Kervtesnage « t J 5 oe Lets pet some understanding ofthe remote atsbute used, othe vey frst parameter “CheckEistingmail” the the ame ofthe ation. The second parsmter “Home” is refered to as contol so ovate the input forthe UserEmalA dress the “CheckExisingEmal” action ofthe “Home” controler is called and ‘he third parameter isthe ear message Lets implemen! the "CheckFxistngEmall” action result nou? home console public Aclontesute Chectbetscangtnail(strig usertnaiaderess) c sfonatlost « Useriattaddress. quals(-eaestirayakqatl-cos") ? true ¢ false Fotunn ston |sfeniliassty Searkeqcrtbonscr Alsons ) catch (exception en) ‘ return 2son{fals,JsorRequestiehavior.ALLowset} , ) eam more here - Remote Valiton in MVC Mvc? 42. What are the Exception filters Answer ‘Exception are pat and pues of an gppiction. They area boon and a ba fran aplication to. Isn't? This would be controversial, for developesit lps ‘hem uack minor and major defects in an application and sometimes they are rusting whea it lt users land onthe Velow scree of death each ime. This ‘would make the users mundane to the application. Ths to avoid this, developers handle the exceptions, But ail somtimes there ara few inbandled xceptions. [Now whats to be dane fr thm? MV provides us with builsin "Exception Firs” aout which we wil explain bee : Google Lets san {A Yellow sereen of Death can be said isa watdobe malfunction of our aplication, Get Started [Exception filters ran when some ofthe exceptions are unhandled and thrown ftom an invoked action, The reason forthe exception canbe anything and ois the soure ofthe exception. Creating an Exception Fier ‘Custoan Exception Filters must implement te buf xcetionFiler interface. The interface looks a inthe following, ots ontcaption(exepttoncontnt ¢4iterCantext) > be ‘Whenever an unhandled exception is encountered, the OnExcepion method gts invoked. The parameter as we can se, ExceptionContxt is deived fiom the CContailerConext and has «nue of builtin propess that canbe used io ge he aformation abou! the vequest causing he exception. Tei propels xceptonContenipassess ae shown in he following abe ‘Name pe Detail Result ‘ActionResult | The esl returned by the ation being invokes, Exception ‘Exception | The unbanded exceptions caused fom the actions inthe applications ExccpionHanded | BOOL | Tisisa very handy property dha tsa bool value (tetas) based on ifthe exception i handled by any ofthe fiers in the applicton or ot. ‘The exception being thrown from te aston is detailed by the Exception property and once handed (i), ten the propery Excepiontanled canbe toggled so thatthe other filters would know if the exception bas bocn already Randle and cancel the other Ger equcts to handle, The pooblem eth itheexoepios re ‘ot handed hen the default MVC behavior shows te dreaded yellow sere of deat. To the user, at makes avery impression onthe users and more Smportnty exposes the spplicaton’s handy end secure information to the susie word hit ay have hackers ad then the eplicaion gts nt the rad 16 hal Thus, the exceptions nocd tobe dealt with very carefully. Le'show oe smal casom exception ite. This filter canbe sored inside the Filles folder in the web project ofthe solution. Lats add illus called CustomExcepsonFilter.c, public eis CostorcceptionFiter: Flleersttrioute, Ibeeptlonriiter public vote onbxceston(tuceptioncontext #Hltercentext) 1 (1ettercantert.eceptiontandeg 68 FiltercontentCaception fs WulReferenceExeption) ‘sttencontentReset = row Redinectsesule(*eustonsrrorage Ate") > ow ‘Lean more here - Exception Fits in MVC 43. What is MVC HTML- Helpers and its Methods? Answer epee methods are ued to render HTML inthe view. Helper methods generates HTML output that spar ofthe view: They provide an advantage over using ‘he HTML elements since they ean be reused eros the wews and ao reqs lest coding, There re sverl bin helper methods that are wed to generate ‘he HTML for some commanly sed HTML clement, ike frm, checkbox, cropdowaist es. Also we ca cteae out awn helper method o generte custom [HIML. Fist we wl ee how to use the bul helper method and then we Will sce how to eteate custom helper methods. landard HimlHelper methods Some ofthe standard elpe methods ae, + ActonLiak: Renders an anchor. 1 BeginForm: Renders HIML form 1 Checkitor: Renders check box. 1 DropDownList Renders dropdown ist. 1 idiot: Renders iden fel 2 Linon: Render ist box. 1 Pasword: Renders Texto for password input 1 RadioButoa: Render ado baton, 1 Textare: Renders ex ate. 1 TenBow: Render textbox, ‘eam more hore HunlHoiper Methods in ASPNET MVC 44, Define Controller in MVC? Answer ‘The conoller provides model dala othe view, and nterpets user actions sch bution clicks, The congller depends onthe view andthe model. In some cates, the controller a the view ar the same object using System; using System Collections Generic; using Systen-Lings using system web; using System.neb.Hves Controller namespace DemsMVC.Controllers { Contrallee public string fnployectimes() 4 Fatun @ul> Acta ‘2i>Seurabh Somanic/13> <1ipSaloni choudhrys/1i> ‘ aor <1ip0inesh Benival «jus > ? y ‘The Controters Folder ‘The Controllers Folder contains the contoller clases responsible for handling user input and responses, MVC requies the name ofall eotoles to nd with "Conor ‘our example, Visual Web Developer has created the following flee: HomeContollcs (for the Home and Abou pages) and AccountContrlle (For the Log On pages) Ape un corer B corer BD recunConbeeres DB Homeconliens a Mewes Serpe Ben 2) Getaaae 1B pectgecontg Bercy ‘Lea mare bore - ASPNet MVC Contoller 45. Explain Model in MVC? Answer ‘The model represents the dat, end does noting eke, The model does NOT depend onthe controler or the view. The MVC Model contin al application logic (osines lng, vaiation loi, and data acces logis), except pe view and contollerlgse. With MVC, models both old and manipulate aplication data, “The Models Folde ‘The Modals Folder contains the clases hat epeset the application mods val Web Developer atomically crests an AccountModels.s filet contsins the models for application secu. Learn more here - Model in ASPNet MVC Past 46. Explain View in MVC? Anwwer A vier is esponsibe for playing al f, or portion of da for users, n simple ers, whatever we see onthe output scresn i view. ‘The Views Fader "The Views folder stores the les (HTML. Ses) related tthe display ofthe application (the wser interfaces). These ile may have the extensions tl, sp asp, him and vhbiml, depending on the language ante, ‘The Views folds contains one elder fr each conuoller. Visual Web Developer as ereted an Account oer, « Home folder, and a Shared folder aside the ‘Views folder) The Account folder contains pape or repisterng at logging into ser accounts. The Home fold is sed for ston application pags ike the home page andthe abot pags, The Share folder is eto store views shard between conrollers (master pages an layout page). ‘Lea mare here - ASP.Net MVC View 47. What is Attribute Routing in MVC? Answer ‘A route atibute is defined on top ofan ation method. The flowing isthe example of Route Atihute in which outings defined where the ation metho i efned Inthe following example, Lam defining the route atibut on op ofthe action method c puns crest {oureclncetore>) bbc rcloenl dex . return ites Auribute Routing with Optional Parameter ‘We can also define an optional parameter i the URL pater by defining mark parametervaluc c to the route parameter, We can also define the dof vale by wing U1 SR veto [Rouretomictore /¢ curtonerne 2)°)] bh aclonesle Otherto inp ctor return vents ° > 11 Opsonal URE Daranater with default valet Uh SR eto [Routetomictast /( curtonerane -0096952)")] public ActiontessSc Otmertort (sting orton ane) t return Wew(}e ° > > be ‘Lea more bere - Atuibute Rosting in ASPNet MVC 5.0 48. Explain RenderSection in MVC? Answer RenderSection( i method ofthe WebPageBase class Sot wrote a one pois, The Fist parameter to the “RenderSection) helper method specifies the mame ofthe section we wan! to render tht location nthe layou emplate. The second parameter option, nd lows us to define wheter te section we ae endering is equited or nt. fa section is required” then Razor wil throw an ero at rtm ia section isnt implemented within a view template thai trae onthe layout ie (hat cat make easier wo tack dom content ror), stu the HTML content to end. eteaeincton tetas" regutreg: f016) poverty) fess Morkop ‘eam more hare - ASTNet MVC 4 - Layout and Section i Raror 49. What is GET and POST Actions Types? Answer cer GET i ued to request data rom a specified resource, With al the GET request we pass the URI. whichis compulsory, however ican ake the flowing overonde evr! f data, ucce(dta, tetas, jgXBR) Jf dataType }) done fal Post POST ie used to submit data to be processed to a specifi resource, With al the POST reqesis we pass he URI which i compulsory and the data, however it can take the following overloads pot ( data} succes, etStansjgXHI) } ( dataType}) Learn more here GET and POST Calls to Contollers Method in MVC 50. What's new in MVC 6? Anewer In MVC 6 Microsoft removed the dependency of System Web Dl from MVS because itso expensive that typically it consume 30k of memory per request and response, whereas now MVC 6 only reqies 2x of memory per request and the respons is avery small memory consumtion. ‘The advange of using the clou-opinized framework shat we an inludea copy ofthe mono CLR with your website Far he sake of ave website we do ot need to upgrade the NET version on the entire machine. A diferent version ofthe CLR fora diferent website mnning side hy side. MVC 6 isa part of ASPNET 5 hates been designed for loud-optimized applications. The rane automaticaly picks the crest version ofthe ibrary When four MVC applieation deployed othe clond ‘The Core CLR i also suppoed tobe tuned wit a high resource-sfisin optimization Microsoft has made many MVC, Web API, WebPage and Signal. specs we cll MVC 6, ‘Most ofthe problems are solved using the Roslyn Compiler. lp ASPNET yNext ues the Roslys Compiler, Using the Roslyn Compiler we donot ne to compile the pplication, automatically emilee the appliction cade, Ys wil eit s code file and can then see the changes by reteshing th browse thot ‘topping or rbulding the project, ‘Rm on hosts other than 1S Where we use MVS we ean hot it on an IS server and we ean also rn it on top ofan ASP. NET Pipeline, on the ater hand MVC 6 bas feature that makes it beter and that feat eel? hosted onan IS server and a seaser pipeline Environment bated configuration system ‘The configuration system provides an envzonment to casily deploy the application onthe cloud. Ou application works jus ike a configuration provide. I helps to etree the vale rom the various configuaton sourees ike XML ile MVC 6 includes anew envconmen- based configuration sytem, Unlike something lei depends on just the Web, Config ile inthe previous version, Dependency injection ‘Using the Service Provider interface we can easily al our own dependency ijetion container. We can replace the del implementation with our own Supports OWIN ‘We have complete corr! over the compossbl pipslin in MVC 6 applications. MVC 6 sappots the OWIN abstraction, [Lea more bere - ASP.Net MVC 6 Now Festres More Interview Questions

You might also like