MVC
-- is open source web application framework.
Advantages of using asp.net mvc
- 1. Views and controllers get connected automatically
2. Multiple GUI platforms supported
3. Platform-independent navigation to views
- Easier to manage the complexity
- Enables the full control over the rendered HTML.
- Provides clean separation of concerns(SoC).
- Enables Test Driven Development (TDD).
- Easy integration with JavaScript frameworks.
- Following the design of stateless nature of the web.
- RESTful urls that enables SEO.
3-tier Architecture
1.Web Platform Installer 5.0(mvc plugin install)
2.Camel type---à
MyFirstApp(Each word first letter caps)
3.MVC5
4.<!DOCTYPE html>
-----------html5
5.<meta charset=”utf-8”>avoid cross site scripting
6.<meta name=”viewport” content=width=”device-width”>
--Responsive
7.index()-----------------------Action
8. default we are using @in viewpage
(v-c-m-c-m-v)
View bag---used to display in controller to view page (ex
viewbag.message)
Controller:
- Default keyword (controller)followed by controller (ex:
HomeController)
- Controller Handle User Interaction logic
- Every public method called as action method
-Create properties prop doubletab
View:
- View means user interface or design
- User interact with server.
- view/currentcontrollerFolder/arguments
- Action to view ----àviewData[“Test”]=”hi”;
-viewBag---ViewBag.Title=”hfhfhf”;
- Razor syntax--à@.....
Model:
Business data and Business logics layout
1.viewResult---Render a complete web page
Ex:Return
view(model)
2.PartialViewResult—render a section of webpage
3.contentResult--- returns user defind,contents,xml
Ex : Return
content(“test”)
4.jsonResult—return Json Result
Ex:
Var
serial=”gfdghfh”;
return Json(new
{name=”serial”, value=serial},JsonRequestBehaviour.AllowGet)
5.RedirectToRouteResult---redirect to another action
Ex:Return
RedirectToAction(“index”)
ASP.NET File Types
The following HTML file types can be found in the Views Folder:
File Type | Extention |
---|---|
Plain HTML | .htm or .html |
Classic ASP | .asp |
Classic ASP.NET | .aspx |
ASP.NET Razor C# | .cshtml |
ASP.NET Razor VB | .vbhtml |
What is the latest version of MVC?
MVC 6 is the latest version which is also termed as ASP VNEXT.What is the difference between each version of MVC 2, 3 , 4, 5 and 6?
MVC 6ASP.NET MVC and Web API has been merged in to one.
Dependency injection is inbuilt and part of MVC.
Side by side - deploy the runtime and framework with your application
Everything packaged with NuGet, Including the .NET runtime itself.
New JSON based project structure.
No need to recompile for every change. Just hit save and refresh the browser.
Compilation done with the new Roslyn real-time compiler.
vNext is Open Source via the .NET Foundation and is taking public contributions.
vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.
MVC 5
One ASP.NET
Attribute based routing
Asp.Net Identity
Bootstrap in the MVC template
Authentication Filters
Filter overrides
MVC 4
ASP.NET Web API
Refreshed and modernized default project templates
New mobile project template
Many new features to support mobile apps
Enhanced support for asynchronous methods
MVC 3
Razor
Readymade project templates
HTML 5 enabled templates
Support for Multiple View Engines
JavaScript and Ajax
Model Validation Improvements
MVC 2
Client-Side Validation
Templated Helpers
Areas
Asynchronous Controllers
Html.ValidationSummary Helper Method
DefaultValueAttribute in Action-Method Parameters
Binding Binary Data with Model Binders
DataAnnotations Attributes
Model-Validator Providers
New RequireHttpsAttribute Action Filter
Templated Helpers
Display Model-Level Errors
What are HTML helpers in MVC?
HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
Hide Copy Code
<%= Html.TextBox("LastName") %>For checkbox below is the HTML helper code. In this way we have HTML helper methods for every HTML control that exists.
Hide Copy Code
<%= Html.CheckBox("Married") %>
What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?
Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.
Hide Copy Code
Html.TextBox("CustomerCode")Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘CustomerCode” from object “m”.
Hide Copy Code
Html.TextBoxFor(m => m.CustomerCode)In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.
Where is the route mapping code written?
The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.Can we map multiple URL’s to the same action?
Yes, you can, you just need to make two entries with different key names and specify the same controller and action.How can we navigate from one view to another using a hyperlink?
By using theActionLink
method as shown in the below
code. The below code will create a simple URL which helps to navigate to
the “Home” controller and invoke the GotoHome
action.
Hide Copy Code
<%= Html.ActionLink("Home","Gotohome") %>
How can we maintain sessions in MVC?
Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.How can we maintain sessions in MVC?
Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.What is the difference between tempdata, viewdata, and viewbag?
Figure: Difference between tempdata, viewdata, and viewbag
- Temp data - Helps to maintain data when you move from one controller to another controller or from one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables.
- View data - Helps to maintain data when you move from controller to view.
- View Bag - It’s a dynamic wrapper around view data. When you use
Viewbag
type, casting is not required. It uses thedynamic
keyword internally.
Figure: dynamic keyword
- Session variables - By using session variables we can maintain data from any entity to any entity.
- Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.
Maintains data between | ViewData/ViewBag | TempData | Hidden fields | Session |
Controller to Controller | No | Yes | No | Yes |
Controller to View | Yes | No | No | Yes |
View to Controller | No | No | Yes | Yes |
What is difference between TempData and ViewData ?
“TempData” maintains data for the complete request while “ViewData” maintains data only from Controller to the view.Does “TempData” preserve data in the next request also?
“TempData” is available through out for the current request and in the subsequent request it’s available depending on whether “TempData” is read or not.So if “TempData” is once read it will not be available in the subsequent request.
What are partial views in MVC?
Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header, and footer as shown in the image below.
Figure: Partial views in MVC
For every page you would like to reuse the left menu, header, and
footer controls. So you can go and create partial views for each of
these items and then you call that partial view in the main view.What is Razor in MVC?
It’s a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor was introduced in MVC 3.Why Razor when we already have ASPX?
Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in ASPX to display simple time, we need to write:
Hide Copy Code
<%=DateTime.Now%>
In Razor, it’s just one line of code:
Hide Copy Code
@DateTime.Now
So which is a better fit, Razor or ASPX?
As per Microsoft, Razor is more preferred because it’s light weight and has simple syntaxes.How can you do authentication and authorization in MVC?
You can use Windows or Forms authentication for MVC.How to implement Windows authentication for MVC?
For Windows authentication you need to modify the web.config file and set the authentication mode to Windows.
Hide Copy Code
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
Then in the controller or on the action, you can use the Authorize
attribute which specifies which users have access to these controllers
and actions. Below is the code snippet for that. Now only the users
specified in the controller and action can access it.
Hide Copy Code
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
How do you implement Forms authentication in MVC?
Forms authentication is implemented the same way as in ASP.NET. The first step is to set the authentication mode equal toForms
. The loginUrl
points to a controller here rather than a page.
Hide Copy Code
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>
We also need to create a controller where we will check if the user
is proper or not. If the user is proper we will set the cookie value.
Hide Copy Code
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") &&
(Request.Form["txtPassword"] == "Shiv@123"))
{
FormsAuthentication.SetAuthCookie("Shiv",true);
return View("About");
}
else
{
return View("Index");
}
}
All the other actions need to be attributed with the Authorize
attribute so that any unauthorized user making a call to these
controllers will be redirected to the controller (in this case the
controller is “Login”) which will do the authentication.
Hide Copy Code
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}
What are the different types of results in MVC?
Note: It’s difficult to remember all the 12 types. But some important ones you can remember for the interview areActionResult
, ViewResult
, and JsonResult
. Below is a detailed list for your interest:There 12 kinds of results in MVC, at the top is the
ActionResult
class which is a base class that can have 11 subtypes as listed below:ViewResult
- Renders a specified view to the response streamPartialViewResult
- Renders a specified partial view to the response streamEmptyResult
- An empty response is returnedRedirectResult
- Performs an HTTP redirection to a specified URLRedirectToRouteResult
- Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route dataJsonResult
- Serializes a givenViewData
object to JSON formatJavaScriptResult
- Returns a piece of JavaScript code that can be executed on the clientContentResult
- Writes content to the response stream without requiring a viewFileContentResult
- Returns a file to the clientFileStreamResult
- Returns a file to the client, which is provided by aStream
FilePathResult
- Returns a file to the client
What are the different types of action filters?
- Authorization filters
- Action filters
- Result filters
- Exception filters
How to send result back in JSON format in MVC
In MVC, we have theJsonResult
class by which we can return back data in JSON format. Below is a simple sample code which returns back a Customer
object in JSON format using JsonResult
.
Hide Copy Code
public JsonResult getCustomer() { Customer obj = new Customer(); obj.CustomerCode = "1001"; obj.CustomerName = "Shiv"; return Json(obj,JsonRequestBehavior.AllowGet); }Below is the JSON output of the above code if you invoke the action via the browser.
Protocols in MVC
GET, POST, PUT, DELETE
No comments:
Post a Comment