7. What is Routing in ASP.NET MVC?
Answer:
The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. Routing is a pattern matching system that monitors the incoming request and figures out what to do with that request.
Routing helps us to define a URL structure and map the URL with the controller.
Below is the code which shows how the URL structure, mapping with controller and action is defined.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
8. Explain attributes based routing in MVC. How to define it?
Answer:
This feature introduces in MVC 5. By using the "Route" attribute we can define URL structure. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.
For example in the below code we have decorated the "GotoContact" action with the route attribute. The route attribute says that the "GotoContact" can be invoked using the URL structure "Users/contact".
public class HomeController : Controller
{
[Route("Users/contact")]
public ActionResult GotoContact()
{
return View();
}
}
public class HomeController : Controller
{
[Route("Users/contact")]
public ActionResult GotoContact()
{
return View();
}
}
{
[Route("Users/contact")]
public ActionResult GotoContact()
{
return View();
}
}
9. How to enable attribute routing in ASP.NET MVC?
Answer:
To enable attribute routing in ASP.NET MVC5 application, we just add a call to routes.MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig.cs file.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enabling attribute routing
routes.MapMvcAttributeRoutes();
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enabling attribute routing
routes.MapMvcAttributeRoutes();
}
}
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enabling attribute routing
routes.MapMvcAttributeRoutes();
}
}
10. What is the difference between Routing and URL rewriting?
Answer:
Routing is focused on mapping a URL to a resource while URL rewriting is focused on mapping one URL (new URL) to another URL (old URL).
URL rewriting rewrites your old URL to new one while routing never rewrites your old URL to new one but it maps to the original route.
11. How can we maintain session in MVC?
Answer:
Sessions can be maintained in MVC by three ways:
- TempData
- ViewData
- ViewBag
12. What is the difference between ViewData, ViewBag and TempData?
Answer:
ViewData:
ViewData helps to maintain data when we move from controller to view. It is derived from the ViewDataDictionary class. It is available for the current request only and also requires typecasting for complex data.
ViewBag:
It also helps to maintain data when we move from controller to view. It uses dynamic keyword internally. It is also available for the current request only and typecasting is not required.
TempData:
It is derived from TempDataDictionary class. Tempdata helps to maintain data when we move from one controller to another controller or from one action to another action. It requires typecasting for complex data.
13. What is Partial View in ASP.NET MVC?
Answer:Partial view is a reusable view (like user control). A partial view is a view that is rendered within another view which means it can be embedded inside other view.
Partial view can be rendered using Html.Partial(), Html.RenderPartial(), Html.RenderAction() method.
14. Explain the difference between View and Partial View?
Answer:View:
- View contains the layout page.
- Before any view is rendered, viewstart page is rendered.
- It is not lightweight as compare to Partial View.
- View might have markup tag like html, head, title, body etc.
- Partial view does not contain layout page.
- We can pass regular view to the render partial method.
- Partial view is designed specially to render within the view and just because of that it does not consist any mark up.
- Partial View is lightweight compared to View.
- Partial view can be embedded inside another view.
15 What are the HTML helpers in ASP.NET MVC?
Answer:Html helpers are a method that returns a HTML string. HTML helpers help us to render HTML controls in the view. HTML helper does not have an event model and a view state.
We can also create our own HTML Helpers to render more complex content.
There are three types of HTML helpers.
i. Inline HTML helpers
ii. Built-in HTML helpers
- Standard HTML helpers
- Strongly type HTML helpers
- Templated HTML Helpers
If we want to add HTML textbox on view, below is the HTML helper.
<%= Html.TextBox("Name") %>
16. What is the difference between "HTML.TextBox" and "HTML.TextBoxFor"?
Answer:HTML.TextBoxFor is strongly type while HTML.TextBox is not, but they both produce same HTML.
1: @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)
will both produce
<input id="Name" name="Name" type="text" />
Using the typed "TextBoxFor" version allows using compile time checking. So if we change our model then we can check whether there are any errors in your views.
17. How can we do validation in ASP.NET MVC?
Answer:ASP.NET MVC uses DataAnnotations attributes to implement validations. It is one of the easiest ways to do validation in MVC.
For example, in the code snippet below we have a simple Employee class with a property EmpCode.
This EmpCode property is tagged with a Required data annotation attribute.
public class Employee
{
[Required(ErrorMessage="Emp code is required")]
public string EmpCode
{
set;
get;
}
}
{
[Required(ErrorMessage="Emp code is required")]
public string EmpCode
{
set;
get;
}
}
In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.
<% using (Html.BeginForm("PostEmployee", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.EmpCode)%>
<%=Html.ValidationMessageFor(m => m.EmpCode)%>
<input type="submit" value="Submit Employee data" />
<%}%>
{ %>
<%=Html.TextBoxFor(m => m.EmpCode)%>
<%=Html.ValidationMessageFor(m => m.EmpCode)%>
<input type="submit" value="Submit Employee data" />
<%}%>
Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.
public ActionResult PostEmployee(Employee obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Employee");
}
}
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Employee");
}
}
18. What is validation summary?
Answer:The validation summary is used to display all the error messages in the view. It displays an unordered list of all validation errors in the ModelState dictionary object.
Example:
@Html.ValidationSummary(true) @*//shows model-level errors*@
@Html.ValidationSummary(false) @*//shows model-level and property-level errors*@
@Html.ValidationSummary(false) @*//shows model-level and property-level errors*@
0 comments:
Post a Comment