Answers: Answer
Answers: Answer
Answers: Answer
The MVC model also provides full control over HTML, CSS, and
JavaScript.
The MVC model defines web applications with 3 logic layers,
The Model is the part of the application that handles the logic for
the application data.
Often model objects retrieve data (and store data) from a database.
The View is the part of the application that handles the display of
the data.
Most often the views are created from the model data.
Typically controllers read data from a view, control user input, and
send input data to the model.
Change Accommodation
User interfaces tend to change more frequently than business
rules (different colors, fonts, screen layouts, and levels of
support for new devices such as cell phones or PDAs)
because the model does not depend on the views, adding new
types of views to the system generally does not affect the
model. As a result, the scope of change is confined to the
view.
More Control
Testability
ASP.NET MVC framework provides better testability of the Web
Application and good support for the test driven development too.
Lightweight
Answer
Any web application has two main execution steps, first
understanding the request and depending on the type of the
request sending out appropriate response. MVC application life
cycle is not different it has two main phases, first creating the
request object and second sending our response to the browser.
The request object creation has four major steps. The following is
the detailed explanation of the same.
This phase has two steps executing the action and finally sending
the response as a result to the view.
Here is a complete article on ASP.Net MVC Life Cycle.
There are total nine return types we can use to return results from
controller to view.
1. ViewResult (View)
This return type is used to return a webpage from an action
method.
2. PartialviewResult (Partialview)
This return type is used to send a part of a view which will be
rendered in another view.
3. RedirectResult (Redirect)
This return type is used to redirect to any other controller and
action method depending on the URL.
6. jsonResult (json)
This return type is used when we want to return a JSON
message.
7. javascriptResult (javascript)
This return type is used to return JavaScript code that will run
in browser.
8. FileResult (File)
This return type is used to send binary output in response.
9. EmptyResult
This return type is used to return nothing (void) in the result.
Types of Filters
Authorization Filters
Authorization filters are used to implement authentication and
authorization for controller actions.
Result Filters
Result filters contain logic that is executed before and after a
view result is executed. For example, you might want to
modify a view result right before the view is rendered to the
browser.
Exception Filters
Exception filters are the last type of filter to run. You can use
an exception filter to handle errors raised by either your
controller actions or controller action results. You can also use
exception filters to log errors.
Handle Error
This action filter handles errors raised when a controller action
executes.
Authorize
This action filter enables you to restrict access to a particular
user or role.
Output Cache
Code Example
1. publicclassActionFilterDemoController: Controller
2. {
3. [HttpGet]
4. OutputCache(Duration = 10)]
5. publicstringIndex()
6. {
7. returnDateTime.Now.ToString("T");
8.
9. }
10. }
Answer
1. ControllerName
2. ActionMethodName
3. Parammeter
Code Example
You add the route to the application by adding the Route object to
the static Routes property of the RouteTable class. The
Routesproperty is a RouteCollection object that stores all the routes
for the application.
Default Route
URL: "{controller}/{action}/{id}"
This route pattern is registered via call to the MapRoute() extension
method of RouteCollection.
Answer
ViewData
ViewBag
Answer
View
Partial View
With MVC, HTML helpers are much like traditional ASP.NET Web
Form controls.
Just like web form controls in ASP.NET, HTML helpers are used to
modify HTML. But HTML helpers are more lightweight. Unlike Web
Form controls, an HTML helper does not have an event model and
a view state.
In most cases, an HTML helper is just a method that returns a
string.
With MVC, you can create your own helpers, or use the built in
HTML helpers.
HTML Links
ASP Syntax
The first parameter is the link text, and the second parameter is the
name of the controller action.
Property Description.
.linkText The link text (label).
.actionName The target action.
.routeValues The values passed to the action.
.controllerName The target controller.
.htmlAttributes The set of attributes to the link.
.protocol The link protocol.
.hostname The host name for the link.
.fragment The anchor target for the link.
BeginForm()
EndForm()
TextArea()
TextBox()
CheckBox()
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()
ASP.NET Syntax C#
Example
Why is Razor?
The Razor View Engine is a bit slower than the ASPX View Engine.
Conclusion
C# Example
1. <system.web>
2. <authenticationmode="Forms">
3. <formsloginUrl="Login.aspx" protection="Al
l" timeout="30" name=".ASPXAUTH" path="/" requireS
SL="false" slidingExpiration="true" defaultUrl="de
fault.aspx" cookieless="UseDeviceProfile" enableCr
ossAppRedirects="false" />
4. </authentication>
5. </system.web>
When you add an area to a project, a route for the area is defined in
an AreaRegistration file. The route sends requests to the area
based on the request URL. To register routes for areas, you add
code to theGlobal.asax file that can automatically find the area
routes in the AreaRegistration file.
AreaRegistration.RegisterAllAreas();
Create
It creates a View that helps in creating a new record for the Model.
It automatically generates a label and input field for each property in
the Model.
Delete
It creates a list of records from the model collection along with the
delete link with delete record.
Details
It generates a view that displays the label and an input field of the
each property of the Model in the MVC framework.
Edit
It creates a View with a form that helps in editing the current Model.
It also generates a form with label and field for each property of the
model.
List
It generally creates a View with the help of a HTML table that lists
the Models from the Model Collection. It also generates a HTML
table column for each property of the Model.
So, we want to set some constraint string after our host name. Fine,
let's see how to implement it.
It's very simple to implement, just open the RouteConfig.cs file and
you will find the routing definition in that. And modify the routing
entry as in the following. We will see that we have added “abc”
before.
Learn more here - Getting Started with Razor View Engine in MVC
3
1. Any
2. Client
3. Downstream
4. Server
5. None
6. ServerAndClient
With "Any", the output cache is stored on the server where the
request was processed. The recommended store cache is always
on the server very carefully. You will learn about some security
related tips in the following "Don't use Output Cache".
Bundling
Minification
It squeezes out whitespace and performs other types of
compression to make the downloaded files as small as possible. At
runtime, the process identifies the user agent, for example IE,
Mozilla, etc. and then removes whatever is specific to Mozilla when
the request comes from IE.
Database First
Model First
Code First
Model
Controllers
These are the classes which will perform the action invoked by the
user. These classes contains methods known as "Actions" which
responds to the user action accordingly.
Views
These are simple pages which uses the model class data to
populate the HTML controls and renders it to the client browser.
App_Start
9. RegisterRoutes(RouteTable.Routes);
10. }
The HandleError Error attribute has a couple for properties that are
very useful in handling the exception.
ExceptionType
View
Master
Master View for displaying the exception.
Order
Order in which the action filters are executed. The Order property
has an integer value and it specifies the priority from 1 to any
positive integer value. 1 means highest priority and the greater the
value of the integer is, the lower is the priority of the filter.
AllowMultiple
Example
1. [HandleError(View = "Error")]
2. public class HomeController: Controller
3. {
4. public ActionResult Index()
5. {
6. ViewBag.Message = "Welcome to ASP.NET MVC!
";
7. int u = Convert.ToInt32(""); // Error line
8. return View();
9. }
10. }
1. [HandleError(View = "Error")]
2. public ActionResult Index()
3. {
4. ViewBag.Message = "Welcome to ASP.NET MVC!";
5. int u = Convert.ToInt32(""); // Error line
6. return View();
7. }
There are three options in Model View Controller (MVC) for passing
data from controller to view. This article attempts to explain the
differences among ViewData, ViewBag and TempData with
examples. ViewData and ViewBag are similar and TempData
performs additional responsibility. The following are the key points
on those three objects.
ViewData
ViewBag
TempData
Prerequisites
Example of Viewstart
1. @ {
2. Layout = "~/Views/Shared/_v1.cshtml";
3. } < !DOCTYPE html >
4. < html >
5. < head >
6. < meta name = "viewport"
7. content = "width=device-width" / >
8. < title > ViewStart < /title> < /head> < body
>
9. < /body> < /html>
1. @ {
2. ViewBag.Title = "Student Summary";
3. var student = ViewBag.Student;
4. }
5. < table >
6. < tr >
7. < th > Name < /th> < th > Age < /th> < th > Ci
ty < /th> < /tr> < tr >
8. < td > @student.Name < /td> < td > @student.Ag
e < /td> < td > @student.City < /td> < /tr>
9. < /table>
Here we used one more thing, "ViewBag.Title", that shows the title
of the page.
ViewBag.Name = "Yogesh";
Calling of ViewDatais :
ViewData["Name"] = "yogesh";
2. RegularExpression
Specifies the regular expression to validate the value of the
property.
1. [RegularExpression("[a-z]", ErrorMessage = "Invalid
character")]
3. Range
Specifies the Range of values between which the property
values are checked.
1. [Range(1000,10000,ErrorMessage="Range should be
between 1k & 10k")]
4. StringLength
Specifies the Min & Max length for a string property.
1. [StringLength(50, MinimumLength = 5, ErrorMessage =
"Minimum char is 5 and maximum char is 10")]
5. MaxLength
Specifies the Max length for the property value.
1. [MaxLength(10,ErrorMessage="Customer Code is
exceeding")]
6. MinLength
It is used to check for minimum length.
1. [MinLength(5, ErrorMessage = "Customer Code is too
small")]
1. <system.web>
2. <customErrors mode="On">
3. </system.web>
1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }
1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError(View = "CustomErrorView")]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }
I create a User class under the Models folder. The User class has
two properties "Name" and "Email". The "Name" field has required
field validations while the "Email" field has Email validation. So let's
see the procedure to implement the validation. Create the User
Model as in the following,
1. namespace ServerValidation.Models
2. {
3. public class User
4. {
5. public string Name
6. {
7. get;
8. set;
9. }
10. public string Email
11. {
12. get;
13. set;
14. }
15. }
16. }
1. using System.Text.RegularExpressions;
2. using System.Web.Mvc;
3. namespace ServerValidation.Controllers
4. {
5. public class UserController: Controller
6. {
7. public ActionResult Index()
8. {
9. return View();
10. }
11. [HttpPost]
12. public ActionResult Index(ServerValid
ation.Models.User model)
13. {
14.
15. if (string.IsNullOrEmpty(model.Na
me))
16. {
17. ModelState.AddModelError("Nam
e", "Name is required");
18. }
19. if (!string.IsNullOrEmpty(model.E
mail))
20. {
21. string emailRegex = @ "^([a-
zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
22. @ "\.[0-9]{1,3}\.[0-
9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
23. @ ".)+))([a-zA-Z]{2,4}|[0-
9]{1,3})(\]?)$";
24. Regex re = new Regex(emailReg
ex);
25. if (!re.IsMatch(model.Email))
26. {
27. ModelState.AddModelError(
"Email", "Email is not valid");
28. }
29. } else {
30. ModelState.AddModelError("Ema
il", "Email is required");
31. }
32. if (ModelState.IsValid)
33. {
34. ViewBag.Name = model.Name;
35. ViewBag.Email = model.Email;
36. }
37. return View(model);
38. }
39. }
40. }
1. @model ServerValidation.Models.User
2. @ {
3. ViewBag.Title = "Index";
4. }
5. @using(Html.BeginForm())
6. {
7. if (@ViewData.ModelState.IsValid)
8. {
9. if (@ViewBag.Name != null)
10. { < b >
11. Name: @ViewBag.Name < br / >
18. @if(!ViewData.ModelState.IsValid)
19. {
20. < span class = "field-validation-
error" > @ViewData.ModelState["Name"].Errors[0].Er
rorMessage < /span>
21.
22. }
23. < /div> < div class = "editor-label" >
24.
27. @if(!ViewData.ModelState.IsValid)
28. {
29. < span class = "field-validation-
error" > @ViewData.ModelState["Email"].Errors[0].E
rrorMessage < /span>
30. }
31. < /div> < p >
32. < input type = "submit"
33. value = "Create" / >
34. < /p> < /fieldset>
35. }
Practical Explanation
Let's start!
Get Started
The controller provides model data to the view, and interprets user
actions such as button clicks. The controller depends on the view
and the model. In some cases, the controller and the view are the
same object.
The Controllers Folder
The model represents the data, and does nothing else. The model
does NOT depend on the controller or the view. The MVC Model
contains all application logic (business logic, validation logic, and
data access logic), except pure view and controller logic. With MVC,
models both hold and manipulate application data.
A view is responsible for displaying all of, or a portion of, data for
users. In simple terms, whatever we see on the output screen is a
view.
The Views folder stores the files (HTML files) related to the display
of the application (the user interfaces). These files may have the
extensions html, asp, aspx, cshtml, and vbhtml, depending on the
language content.
The Views folder contains one folder for each controller. Visual Web
Developer has created an Account folder, a Home folder, and a
Shared folder (inside the Views folder). The Account folder contains
pages for registering and logging in to user accounts. The Home
folder is used for storing application pages like the home page and
the about page. The Shared folder is used to store views shared
between controllers (master pages and layout pages).
Learn more here - ASP.Net MVC View
1. <div id="body">
2. @RenderSection("featured", required: false)
3. <section class="content-wrapper main-
content clear-fix">
4. @RenderBody()
5. </section>
6. </div>
GET
GET is used to request data from a specified resource. With all the
GET request we pass the URL which is compulsory, however it can
take the following overloads.
POST
Dependency injection
Supports OWIN
3. Question 3. Do You Know About The New Features In Asp.net Mvc 4 (asp.net
Mvc4)?
Answer :
Following are features added newly : Mobile templates Added ASP.NET Web API
template for creating REST based services. Asynchronous controller task support.
Bundling of the java scripts. Segregating the configs for ASP.Net MVC routing, Web API,
Bundle etc.
4. Question 4. How Does The 'page Lifecycle' Of Asp.net Mvc Works?
Answer :
Below are the processed followed in the sequence :
o App initializWhat is Separation of Concerns in ASP.NET ASP.Net MVCation
o Routing
o Instantiate and execute controller
o Locate and invoke controller action
o Instantiate and render view.
VB.NET Tutorial
ASP.NET Tutorial
17. Question 17. How Route Table Has Been Created In Asp.net Asp.net Mvc?
Answer :
Method : "RegisterRoutes()" is used for registering the routes which will be added in
"Application_Start()" method of global.asax file, which is fired when the application is
loaded or started.
18. Question 18. Which Are The Important Namespaces Used In Asp.net Mvc?
Answer :
Below are the important namespaces used in ASP.Net MVC :
o System.Web.ASP.Net MVC
o System.Web.ASP.Net MVC.Ajax
o System.Web.ASP.Net MVC.Html
o System.Web.ASP.Net MVC.Async
C#. NET Interview Questions
19. Question 19. What Is Viewdata?
Answer :
Viewdata contains the key, value pairs as dictionary and this is derived from class :
"ViewDataDictionary". In action method we are setting the value for viewdata and in view
the value will be fetched by typecasting.
20. Question 20. What Is The Difference Between Viewbag And Viewdata In Asp.net
Mvc?
Answer :
ViewBag is a wrapper around ViewData, which allows to create dynamic properties.
Advantage of viewbag over viewdata will be : In ViewBag no need to typecast the objects
as in ViewData. ViewBag will take advantage of dynamic keyword which is introduced in
version 4.0. But before using ViewBag we have to keep in mind that ViewBag is slower
than ViewData.
24. Question 24. What Are The Options Can Be Configured In Ajax Helpers?
Answer :
Below are the options in AJAX helpers :
Url : This is the request URL.
Confirm : This is used to specify the message which is to be displayed in confirm box.
OnBegin : Javascript method name to be given here and this will be called before the
AJAX request.
OnComplete : Javascript method name to be given here and this will be called at the end
of AJAX request.
OnSuccess - Javascript method name to be given here and this will be called when AJAX
request is successful.
OnFailure - Javascript method name to be given here and this will be called when AJAX
request is failed.
UpdateTargetId : Target element which is populated from the action returning HTML.
ASP.NET Interview Questions
27. Question 27. Can You Explain Renderbody And Renderpage In Asp.net Mvc?
Answer :
RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it
will render the child pages/views. Layout page will have only one RenderBody() method.
RenderPage also exists in Layout page and multiple RenderPage() can be there in Layout
page.
43. Question 43. What Are The Components Required To Create A Route In Asp.net
Mvc?
Answer :
Name - This is the name of the route.
URL Pattern : Placeholders will be given to match the request URL pattern.
Defaults :When loading the application which controller, action to be loaded along with
the parameter.
44. Question 44. Why To Use "{resource}.axd/{*pathinfo}" In Routing In Asp.net Mvc?
Answer :
Using this default route - {resource}.axd/{*pathInfo}, we can prevent the requests for the
web resources files like - WebResource.axd or ScriptResource.axd from passing to a
controller.
45. Question 45. Can We Add Constraints To The Route? If Yes, Explain How We Can
Do It?
Answer :
Yes we can add constraints to route in following ways :
o Using Regular Expressions
o Using object which implements interface - IRouteConstraint.
46. Question 46. What Are The Possible Razor View Extensions?
Answer :
Below are the two types of extensions razor view can have :
.cshtml : In C# programming language this extension will be used.
.vbhtml - In VB programming language this extension will be used.
47. Question 47. What Is Partialview In Asp.net Mvc?
Answer :
PartialView is similar to UserControls in traditional web forms. For re-usability purpose
partial views are used. Since it's been shared with multiple views these are kept in shared
folder.
Partial Views can be rendered in following ways :
o Html.Partial()
o Html.RenderPartial()
48. Question 48. How We Can Add The Css In Asp.net Mvc?
Answer :
Below is the sample code snippet to add css to razor views : < link rel="StyleSheet"
href="/@Href(~Content/Site.css")" type="text/css"/>
49. Question 49. Can I Add Asp.net Mvc Testcases In Visual Studio Express?
Answer :
No. We cannot add the test cases in Visual Studio Express edition it can be added only in
Professional and Ultimate versions of Visual Studio.
50. Question 50. What Is The Use .glimpse In Asp.net Mvc?
Answer :
Glimpse is an open source tool for debugging the routes in ASP.Net MVC. It is the client
side debugger. Glimpse has to be turned on by visiting to local url link -
http://localhost:portname//glimpse.axd This is a popular and useful tool for debugging
which tracks the speed details, url details etc.
51. Question 51. What Is The Need Of Action Filters In Asp.net Mvc?
Answer :
Action Filters allow us to execute the code before or after action has been executed. This
can be done by decorating the action methods of controls with ASP.Net MVC attributes.
52. Question 52. Mention Some Action Filters Which Are Used Regularly In Asp.net
Mvc?
Answer :
Below are some action filters used :
o Authentication
o Authorization
o HandleError
o OutputCache
53. Question 53. How Can We Determine Action Invoked From Http Get Or Http Post?
Answer :
This can be done in following way : Use class : "HttpRequestBase" and use the method :
"HttpMethod" to determine the action request type.
54. Question 54. In Server How To Check Whether Model Has Error Or Not In Asp.net
Mvc?
Answer :
This can be done in following way : Use class : "HttpRequestBase" and use the method :
"HttpMethod" to determine the action request type.
55. Question 55. How To Make Sure Client Validation Is Enabled In Asp.net Mvc?
Answer :
In Web.Config there are tags called : "ClientValidationEnabled" and
"UnobtrusiveJavaScriptEnabled". We can set the client side validation just by setting these
two tags "true", then this setting will be applied at the application level.
< add key="ClientValidationEnabled" value="true" />
< add key="UnobtrusiveJavaScriptEnabled" value="true" />
56. Question 56. What Are Model Binders In Asp.net Mvc?
Answer :
For Model Binding we will use class called : "ModelBinders", which gives access to all
the model binders in an application. We can create a custom model binders by inheriting
"IModelBinder".
57. Question 57. How We Can Handle The Exception At Controller Level In Asp.net
Mvc?
Answer :
Exception Handling is made simple in ASP.Net MVC and it can be done by just
overriding "OnException" and set the result property of the filtercontext object (as shown
below) to the view detail, which is to be returned in case of exception.
protected overrides void OnException(ExceptionContext filterContext)
{
}
58. Question 58. Does Tempdata Hold The Data For Other Request In Asp.net Mvc?
Answer :
If Tempdata is assigned in the current request then it will be available for the current
request and the subsequent request and it depends whether data in TempData read or not.
If data in Tempdata is read then it would not be available for the subsequent requests.
59. Question 59. Explain Keep Method In Tempdata In Asp.net Mvc?
Answer :
As explained above in case data in Tempdata has been read in current request only then
"Keep" method has been used to make it available for the subsequent request.
@TempData["TestData"];
TempData.Keep("TestData");
60. Question 60. Explain Peek Method In Tempdata In Asp.net Mvc?
Answer :
Similar to Keep method we have one more method called "Peek" which is used for the
same purpose. This method used to read data in Tempdata and it maintains the data for
subsequent request.
string A4str = TempData.Peek("TT").ToString();
61. Question 61. What Is Area In Asp.net Mvc?
Answer :
Area is used to store the details of the modules of our project. This is really helpful for big
applications, where controllers, views and models are all in main controller, view and
model folders and it is very difficult to manage.
62. Question 62. How We Can Register The Area In Asp.net Mvc?
Answer :
When we have created an area make sure this will be registered in "Application_Start"
event in Global.asax.
Below is the code snippet where area registration is done :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}
63. Question 63. What Are Child Actions In Asp.net Mvc?
Answer :
To create reusable widgets child actions are used and this will be embedded into the parent
views. In ASP.Net MVC Partial views are used to have reusability in the application.
Child action mainly returns the partial views.
64. Question 64. How We Can Invoke Child Actions In Asp.net Mvc?
Answer :
"ChildActionOnly" attribute is decorated over action methods to indicate that action
method is a child action. Below is the code snippet used to denote the child action :
[ChildActionOnly]
public ActionResult MenuBar()
{
//Logic here
return PartialView();
}
65. Question 65. What Is Dependency Injection In Asp.net Mvc?
Answer :
it's a design pattern and is used for developing loosely couple code. This is greatly used in
the software projects. This will reduce the coding in case of changes on project design so
this is vastly used.
66. Question 66. Explain The Advantages Of Dependency Injection (di) In Asp.net Mvc?
Answer :
Below are the advantages of DI :
o Reduces class coupling
o Increases code reusing
o Improves code maintainability
o Improves application testing
67. Question 67. Explain Test Driven Development (tdd) ?
Answer :
TDD is a methodology which says, write your tests first before you write your code. In
TDD, tests drive your application design and development cycles. You do not do the
check-in of your code into source control until all of your unit tests pass.
68. Question 68. Explain The Tools Used For Unit Testing In Asp.net Mvc?
Answer :
Below are the tools used for unit testing :
o NUnit
o xUnit.NET
o Ninject 2
o Moq
69. Question 69. What Is Representational State Transfer (rest) Mean?
Answer :
REST is an architectural style which uses HTTP protocol methods like GET, POST, PUT,
and DELETE to access the data. ASP.Net MVC works in this style. In ASP.Net MVC 4
there is a support for Web API which uses to build the service using HTTP verbs.
70. Question 70. How To Use Jquery Plugins In Asp.net Mvc Validation?
Answer :
We can use dataannotations for validation in ASP.Net MVC. If we want to use validation
during runtime using Jquery then we can use Jquery plugins for validation.
Eg:
If validation is to be done on customer name textbox then we can do as :
$('#CustomerName').rules("add", {
required: true,
minlength: 2,
messages: {
required: "Please enter name",
minlength: "Minimum length is 2"
}
});
71. Question 71. How We Can Multiple Submit Buttons In Asp.net Mvc?
Answer :
Below is the scenario and the solution to solve multiple submit buttons issue.
Scenario :
@using (Html.BeginForm("MyTestAction","MyTestController")
{
<input type="submit" value="MySave" />
<input type="submit" value="MyEdit" />
} Solution :
Public ActionResult MyTestAction(string submit) //submit will have value either
"MySave" or "MyEdit"
{
// Write code here
}
72. Question 72. What Are The Differences Between Partial View And Display Template
And Edit Templates In Asp.net Mvc?
Answer :
Display Templates : These are model centric. Meaning it depends on the properties of the
view model used. It uses convention that will only display like divs or labels.
Edit Templates : These are also model centric but will have editable controls like
Textboxes.
Partial View : These are view centric. These will differ from templates by the way they
render the properties (Id's) Eg : CategoryViewModel has Product class property then it
will be rendered as Model.Product.ProductName but in case of templates if we
CategoryViewModel has List then @Html.DisplayFor(m => m.Products) works and it
renders the template for each item of this list.
73. Question 73. Can I Set The Unlimited Length For "maxjsonlength" Property In
Config?
Answer :
No. We can't set unlimited length for property maxJsonLength. Default value is - 102400
and maximum value what we can set would be : 2147483644.
74. Question 74. Can I Use Razor Code In Javascript In Asp.net Mvc?
Answer :
Yes. We can use the razor code in javascript in cshtml by using <text> element.
< script type="text/javascript">
@foreach (var item in Model) {
< text >
//javascript goes here which uses the server values
< text >
}
< script>
75. Question 75. How Can I Return String Result From Action In Asp.net Mvc?
Answer :
Below is the code snippet to return string from action method :
public ActionResult TestAction() {
return Content("Hello Test !!");
}
76. Question 76. How To Return The Json From Action Method In Asp.net Mvc?
Answer :
Below is the code snippet to return string from action method :
public ActionResult TestAction() {
return JSON(new { prop1 = "Test1", prop2 = "Test2" });
}