1) How to Rnder HTML to view pages from controller ?
Example
<div>@Html.Raw(ViewBag.Message)</div>
Here Html.Raw is the command to render html to view .The Htnl soure can be database , or any other source.We can use Viewdata["example"] to render in the same manner.
2)MVC Routing
http://www.codeproject.com/Articles/641783/Customizing-Routes-in-ASP-NET-MVC
3)ViewData ViewData is a dictionary object that is derived from ViewDataDictionary class.
ViewData is used to pass data from controller to corresponding view.
It’s life lies only during the current request.
If redirection occurs then it’s value becomes null.
It’s required typecasting for getting data and check for null values to avoid error.
ViewBag ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
It’s life also lies only during the current request.
If redirection occurs then it’s value becomes null.
It doesn’t required typecasting for getting data.
TempData
TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
It’s life is very short and lies only till the target view is fully loaded.
It’s required typecasting for getting data and check for null values to avoid error.
It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article
4)The Simplest way to Display text in MVC
@Html.DisplayText("This MVC control For Display")
5) Html.Encode
HTML-encodes a string and returns the encoded string.
Result.Text = Server.HtmlEncode("<script>unsafe</script>");
One of the best features in the Razor View Engine that I like most is "HTML Encoding". In many cases (like a comment form in a blog) we receive the data from users and he may be trying to harm us by sending some malicious scripts to cause cross-site script injection attacks (aka XSS attack).In ASP.NET Web Forms we have a couple of ways to do HTML encoding:
ASP.NET MVC Razor expressions are automatically HTML encoded. It is always a good practice to validate data received from a user before storing it in the database because the database can accept any malicious data, especially XSS data happily but if you are using Razor to display the data on the web page then you are still safe and you don't need any special care.
6)RenderBody, RenderPage ,RenderPaertial and RenderSection
The page content will be rendered here.
@RenderBody ()
RenderSection
One of the drawbacks of the RenderPage method is that it cannot manage optional content for example you might have a sidebar but don’t want to render it on every page. Sections are a way around this.
The RenderSection method takes two arguments first is the section name and second one is Boolean which specifies if the section is required or not, default is true so it will be required. The diagram below shows how sections work, similar to layout pages.
7)Is there any difference between HTML.ActionLink vs Url.Action or they are just two ways of doing the same thing?
Yes, there is a difference.
For example:
8)Helper Classes
There are several Helper classes in MVC frame work.
1.Form Helper- Radio buttons, textboxes,list boxes etc.
2.URL helpers
3.HTML helpers- Encode, Decode, AttributeEncode, and RenderPartial.
10)What is the difference between @Html.Action & @Html.RenderAction ?
@Html.RenderAction(Action, Controller, Route)
@Html.Action("Breadcrumb", "Navigation", new {SeoUrl = Model.CarlineBucket.SEOURLName})
@Html.RenderAction("Breadcrumb", "Navigation", new {SeoUrl = Model.CarlineBucket.SEOURLName})
The difference between the two is that Html.RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html.Action returns a string with the result.
11) What is the difference between @Html.Parcial and @Html.Renderparcial
The code below demonstrates the call to render the featured product partial view.
<div>
@Html.Partial("_FeaturedProduct")
</div>
Partial views can be rendered inside a Layout Page (or if using MVC 2/3 w/ASPX, the Master Page) as well as regular views.
There are some cases where you might like to step aside and write directly to the HTTP Response stream rather than having a partial view render the results (partials/views use MvcHtmlString/StringWriter). To do so, use the Html.RenderPartial helper.
As with strongly typed views, strongly typed partial views also support dot notation syntax and access to the model, ViewBag, ViewData and other classes specifically designed for sharing data.
For Example
<div>
<div>
<h2>Our Featured product:<br />
@ViewBag.FeaturedProduct.Name
</h2>
</div> <div>
<h3>
Now discounted to $@String.Format("{0:F}", ((decimal)ViewBag.FeaturedProduct.Price)-100)
</h3>
</div>
12) MVC Points to ponder
i. All Html helper classes are static.
ii. All helper methods are static.
iii. One of the parameters of helper method should be HTMLHelper object.
iv. The return type of every Html helper method will be "MVCHtmlString"
v. Add the reference of Helper class project to current MVC project. Include the namespace of html helper class in web.config of MVC app.
14) Advantages of MVC Pattern
15) Mention some of the return types of a controller action method ?
An action method is used to return an instance of any class which is derived from ActionResult class.
Some of the return types of a controller action method are:
i) ViewResult : It is used to return a webpage from an action method
ii) PartialViewResult : It is used to send a section of a view to be rendered inside another view.
iii) JavaScriptResult : It is used to return JavaScript code which will be executed in the user’s browser.
iv) RedirectResult : Based on a URL, It is used to redirect to another controller and action method.
v) ContentResult : It is an HTTP content type may be of text/plain. It is used to return a custom content type as a result of the action method.
vi) JsonResult : It is used to return a message which is formatted as JSON.
vii) FileResult : It is used to send binary output as the response.
viii) EmptyResult : It returns nothing as the result.
16)Explain about 'page lifecycle' of ASP.NET MVC ?
The page lifecycle of an ASP.NET MVC page is explained as follows:
i) App Initialisation
In this stage, the aplication starts up by running Global.asax’s Application_Start() method.
In this method, you can add Route objects to the static RouteTable.Routes collection.
If you’re implementing a custom IControllerFactory, you can set this as the active controller factory by assigning it to the System.Web.Mvc.ControllerFactory.Instance property.
ii) Routing
Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL pattern.
MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers configured in the Routes table.
iii) Instantiate and Execute Controller
At this stage, the active IControllerFactory supplies an IController instance.
iv) Locate and invoke controller action
At this stage, the controller invokes its relevant action method, which after further processing, calls RenderView().
v) Instantiate and render view
At this stage, the IViewFactory supplies an IView, which pushes response data to the IHttpResponse object.
17) Explain about the formation of Router Table in ASP.NET MVC ?
The Router Table is formed by following the below procedure:
In the begining stage, when the ASP.NET application starts, the method known as Application_Start() method is called.
The Application_Start() will then calls RegisterRoutes() method.
This RegisterRoutes() method will create the Router table.
18) Explain about default route, {resource}.axd/{*pathInfo} ...
With the help of this default route {resource}.axd/{*pathInfo}, you can prevent requests for the web resources files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
19)Is the route {controller}{action}/{id} a valid route definition or not and why ?
{controller}{action}/{id} is not a valid route definition.
The reason is that, it has no literal value or delimiter between the placeholders.
If there is no literal, the routing cannot determine where to seperate the value for the controller placceholder from the value for the action placeholder.
20) Difference between Viewbag and Viewdata in ASP.NET MVC ?
Both are used to pass the data from controllers to views.
The difference between Viewbag and Viewdata in ASP.NET MVC is explained below:
View Data:
In this, objects are accessible using strings as keys.
Example:
In the Controller:
public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};
ViewData["softwareDevelopers"] = softwareDevelopers;
return View();
}
In the View:
<ul>
@foreach (var developer in (List<string>)ViewData["softwareDevelopers"])
{
<li>
@developer
</li>
}
</ul>
An important note is that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object.
View Bag:
It will allow the objectto dynamically have the properties add to it.
Example:
In the Controller:
public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};
ViewBag.softwareDevelopers = softwareDevelopers;
return View();
}
In the View:
<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
<li>
@developer
</li>
}
</ul>
An important point to note is that there is no need to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type.
2)Where is the route mapping code written?
3)How to implement AJAX in MVC
4)How do we implement minification?
5)What is Razor in MVC?
6)Can we map multiple URLs to the same action?
7)So which is a better fit, Razor or ASPX?
Example
<div>@Html.Raw(ViewBag.Message)</div>
Here Html.Raw is the command to render html to view .The Htnl soure can be database , or any other source.We can use Viewdata["example"] to render in the same manner.
2)MVC Routing
http://www.codeproject.com/Articles/641783/Customizing-Routes-in-ASP-NET-MVC
3)ViewData ViewData is a dictionary object that is derived from ViewDataDictionary class.
ViewData is used to pass data from controller to corresponding view.
It’s life lies only during the current request.
If redirection occurs then it’s value becomes null.
It’s required typecasting for getting data and check for null values to avoid error.
ViewBag ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
It’s life also lies only during the current request.
If redirection occurs then it’s value becomes null.
It doesn’t required typecasting for getting data.
TempData
TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
It’s life is very short and lies only till the target view is fully loaded.
It’s required typecasting for getting data and check for null values to avoid error.
It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article
4)The Simplest way to Display text in MVC
@Html.DisplayText("This MVC control For Display")
5) Html.Encode
HTML-encodes a string and returns the encoded string.
Result.Text = Server.HtmlEncode("<script>unsafe</script>");
One of the best features in the Razor View Engine that I like most is "HTML Encoding". In many cases (like a comment form in a blog) we receive the data from users and he may be trying to harm us by sending some malicious scripts to cause cross-site script injection attacks (aka XSS attack).In ASP.NET Web Forms we have a couple of ways to do HTML encoding:
ASP.NET MVC Razor expressions are automatically HTML encoded. It is always a good practice to validate data received from a user before storing it in the database because the database can accept any malicious data, especially XSS data happily but if you are using Razor to display the data on the web page then you are still safe and you don't need any special care.
6)RenderBody, RenderPage ,RenderPaertial and RenderSection
RenderBody
The page content will be rendered here.
@RenderBody ()
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
RenderPageThe RenderPage method allows you to render code from an external page. It is useful if you want to keep the footer and header in separate pages and call them into the layout page. This avoids very long pages and keeps code neat. It is similar to the PHP include function.
- In the shared folder create two new files _Header.cshtml and _Footer.cshtml
- From the layout page copy and remove the content between the <header> tag and place it in the _Header.cshtml do the same for the footer.
@RenderPage("~/shared/_Header.cshtml")
RenderSection
One of the drawbacks of the RenderPage method is that it cannot manage optional content for example you might have a sidebar but don’t want to render it on every page. Sections are a way around this.
The RenderSection method takes two arguments first is the section name and second one is Boolean which specifies if the section is required or not, default is true so it will be required. The diagram below shows how sections work, similar to layout pages.
<aside> @RenderSection("sidebar") </aside>
@RenderSection("sidebar", false)
@section sidebar{ <ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> }
7)Is there any difference between HTML.ActionLink vs Url.Action or they are just two ways of doing the same thing?
Yes, there is a difference.
Html.ActionLink
generates an <a href=".."></a>
tag whereas Url.Action
returns only an url. For example:
@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
generates:<a href="/somecontroller/someaction/123">link text</a>
and Url.Action("someaction", "somecontroller", new { id = "123" })
generates:/somecontroller/someaction/123
8)Helper Classes
There are several Helper classes in MVC frame work.
1.Form Helper- Radio buttons, textboxes,list boxes etc.
2.URL helpers
3.HTML helpers- Encode, Decode, AttributeEncode, and RenderPartial.
9)@Url.Content
Url.Content is used when you wish to resolve a url for any file or
resource on your site and you would pass it the relative path:@Url.Content("~/path/file.htm")
Url.Action is used to resolve an action from a controller such as:@Url.Action("ActionName", "ControllerName", new { variable = value })
You could create a URL that invokes the action with it like this:Url.Action("YourAction", "YourController")
@Url.Content
resolves a virtual path into an absolute path. Example:Url.Content("~/images/image.jpg")
10)What is the difference between @Html.Action & @Html.RenderAction ?
@Html.RenderAction(Action, Controller, Route)
@Html.Action("Breadcrumb", "Navigation", new {SeoUrl = Model.CarlineBucket.SEOURLName})
@Html.RenderAction("Breadcrumb", "Navigation", new {SeoUrl = Model.CarlineBucket.SEOURLName})
The difference between the two is that Html.RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html.Action returns a string with the result.
11) What is the difference between @Html.Parcial and @Html.Renderparcial
The code below demonstrates the call to render the featured product partial view.
<div>
@Html.Partial("_FeaturedProduct")
</div>
Partial views can be rendered inside a Layout Page (or if using MVC 2/3 w/ASPX, the Master Page) as well as regular views.
There are some cases where you might like to step aside and write directly to the HTTP Response stream rather than having a partial view render the results (partials/views use MvcHtmlString/StringWriter). To do so, use the Html.RenderPartial helper.
As with strongly typed views, strongly typed partial views also support dot notation syntax and access to the model, ViewBag, ViewData and other classes specifically designed for sharing data.
For Example
<div>
<div>
<h2>Our Featured product:<br />
@ViewBag.FeaturedProduct.Name
</h2>
</div> <div>
<h3>
Now discounted to $@String.Format("{0:F}", ((decimal)ViewBag.FeaturedProduct.Price)-100)
</h3>
</div>
12) MVC Points to ponder
Html.RenderPartial
- This method result will be directly written to the HTTP response stream means it used the same TextWriter object as used in the current webpage/template.
- This method returns void.
- Simple to use and no need to create any action.
- RenderPartial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example :
In a blog to show comments of an article, we would like to use
RenderPartial method since an article information with comments are
already populated in the view model.
- @{Html.RenderPartial("_Comments");}
- This method is faster than Partial method since its result is directly written to the response stream which makes it fast.
Html.RenderAction
- This method result will be directly written to the HTTP response stream means it used the same TextWriter object as used in the current webpage/template.
- For this method, we need to create a child action for the rendering the partial view.
- RenderAction method is useful when the displaying data in the partial view is independent from corresponding view model.For example :
In a blog to show category list on each and every page, we would like
to use RenderAction method since the list of category is populated by
the different model.
- @{Html.RenderAction("Category","Home");}
- This method is the best choice when you want to cache a partial view.
- This method is faster than Action method since its result is directly written to the HTTP response stream which makes it fast.
Html.Partial
- Renders the partial view as an HTML-encoded string.
- This method result can be stored in a variable, since it returns string type value.
- Simple to use and no need to create any action.
- Partial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example :
In a blog to show comments of an article, we would like to use
RenderPartial method since an article information with comments are
already populated in the view model.
- @Html.Partial("_Comments")
Html.Action
- Renders the partial view as an HtmlString .
- For this method, we need to create a child action for the rendering the partial view.
- This method result can be stored in a variable, since it returns string type value.
- Action method is useful when the displaying data in the partial view is independent from corresponding view model.For example :
In a blog to show category list on each and every page, we would like
to use Action method since the list of category is populated by the
different model.
- @{Html.Action("Category","Home");}
- This method is also the best choice when you want to cache a partial view.
i. All Html helper classes are static.
ii. All helper methods are static.
iii. One of the parameters of helper method should be HTMLHelper object.
iv. The return type of every Html helper method will be "MVCHtmlString"
v. Add the reference of Helper class project to current MVC project. Include the namespace of html helper class in web.config of MVC app.
14) Advantages of MVC Pattern
·
It provides a clean separation of concerns.
·
It is easier to test code that implements this pattern.
·
It promotes better code organization, extensibility, scalability
and code re-use.
·
It facilitates de-coupling the application's layers.
15) Mention some of the return types of a controller action method ?
An action method is used to return an instance of any class which is derived from ActionResult class.
Some of the return types of a controller action method are:
i) ViewResult : It is used to return a webpage from an action method
ii) PartialViewResult : It is used to send a section of a view to be rendered inside another view.
iii) JavaScriptResult : It is used to return JavaScript code which will be executed in the user’s browser.
iv) RedirectResult : Based on a URL, It is used to redirect to another controller and action method.
v) ContentResult : It is an HTTP content type may be of text/plain. It is used to return a custom content type as a result of the action method.
vi) JsonResult : It is used to return a message which is formatted as JSON.
vii) FileResult : It is used to send binary output as the response.
viii) EmptyResult : It returns nothing as the result.
16)Explain about 'page lifecycle' of ASP.NET MVC ?
The page lifecycle of an ASP.NET MVC page is explained as follows:
i) App Initialisation
In this stage, the aplication starts up by running Global.asax’s Application_Start() method.
In this method, you can add Route objects to the static RouteTable.Routes collection.
If you’re implementing a custom IControllerFactory, you can set this as the active controller factory by assigning it to the System.Web.Mvc.ControllerFactory.Instance property.
ii) Routing
Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL pattern.
MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers configured in the Routes table.
iii) Instantiate and Execute Controller
At this stage, the active IControllerFactory supplies an IController instance.
iv) Locate and invoke controller action
At this stage, the controller invokes its relevant action method, which after further processing, calls RenderView().
v) Instantiate and render view
At this stage, the IViewFactory supplies an IView, which pushes response data to the IHttpResponse object.
17) Explain about the formation of Router Table in ASP.NET MVC ?
The Router Table is formed by following the below procedure:
In the begining stage, when the ASP.NET application starts, the method known as Application_Start() method is called.
The Application_Start() will then calls RegisterRoutes() method.
This RegisterRoutes() method will create the Router table.
18) Explain about default route, {resource}.axd/{*pathInfo} ...
With the help of this default route {resource}.axd/{*pathInfo}, you can prevent requests for the web resources files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
19)Is the route {controller}{action}/{id} a valid route definition or not and why ?
{controller}{action}/{id} is not a valid route definition.
The reason is that, it has no literal value or delimiter between the placeholders.
If there is no literal, the routing cannot determine where to seperate the value for the controller placceholder from the value for the action placeholder.
20) Difference between Viewbag and Viewdata in ASP.NET MVC ?
Both are used to pass the data from controllers to views.
The difference between Viewbag and Viewdata in ASP.NET MVC is explained below:
View Data:
In this, objects are accessible using strings as keys.
Example:
In the Controller:
public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};
ViewData["softwareDevelopers"] = softwareDevelopers;
return View();
}
In the View:
<ul>
@foreach (var developer in (List<string>)ViewData["softwareDevelopers"])
{
<li>
@developer
</li>
}
</ul>
An important note is that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object.
View Bag:
It will allow the objectto dynamically have the properties add to it.
Example:
In the Controller:
public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};
ViewBag.softwareDevelopers = softwareDevelopers;
return View();
}
In the View:
<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
<li>
@developer
</li>
}
</ul>
An important point to note is that there is no need to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type.
@Html.Partial
@Html.Partial
1)What is Model view controller ?2)Where is the route mapping code written?
3)How to implement AJAX in MVC
4)How do we implement minification?
5)What is Razor in MVC?
6)Can we map multiple URLs to the same action?
7)So which is a better fit, Razor or ASPX?
No comments:
Post a Comment