Wednesday, August 27, 2014

Let Vs Into Keywords in LINQ

Let Vs Into Keywords in LINQ


Dotnetpiper
This article shows two keywords of LINQ. These keywords are very helpful when working with a set of object collections using LINQ.

First I will go through the Into keyword and its use.

I used the following collection in this article, on which I've done actions in this article.

  1: List<Mobile> objMobileCollection = new List<Mobile>  
  2: {   
  3: new Mobile{Provider="Apple",ModelName="IPhone3",ModelNumber="I100",MemoryCard=4},  
  4: new Mobile{Provider="Apple",ModelName="IPhone4",ModelNumber="I101",MemoryCard=8},  
  5: new Mobile{Provider="Apple",ModelName="IPhone4S",ModelNumber="I102",MemoryCard=16},  
  6: new Mobile{Provider="Apple",ModelName="IPhone5",ModelNumber="I103",MemoryCard=32},  
  7: new Mobile{Provider="Samsung",ModelName="GalaxyS",ModelNumber="S001",MemoryCard=4},  
  8: new Mobile{Provider="Samsung",ModelName="GalaxyS2",ModelNumber="S002",MemoryCard=16},  
  9: new Mobile{Provider="Samsung",ModelName="GalaxyS3",ModelNumber="S003",MemoryCard=20},  
 10: new Mobile{Provider="Samsung",ModelName="Grand",ModelNumber="G001",MemoryCard=4},  
 11: new Mobile{Provider="Nokia",ModelName="LUMIA530",ModelNumber="N1",MemoryCard=8},  
 12: new Mobile{Provider="Nokia",ModelName="LUMIA730",ModelNumber="N2",MemoryCard=16},  
 13: new Mobile{Provider="Nokia",ModelName="LUMIA930",ModelNumber="N3",MemoryCard=20},  
 14: };  

Into keyword
The Into keyword allows creating a temporary variable to store the results of a group, join or select clause into a new variable.
  1: var resultSet = from mobile in objMobileCollection  
  2: group mobile by new { mobile.Provider } into mGroup  
  3: orderby mGroup.Key.Provider  
  4: select new
  5: {  
  6: Provider = mGroup.Key.Provider,  
  7: ModelName = mGroup.OrderBy(x => x.ModelName),  
  8: //ModelNumber = mGroup.OrderBy(x => x.ModelNumber),
  9: //MemoryCard = mGroup.OrderBy(x => x.MemoryCard),
 10: };  
 11: 

In the above query after applying Into on mobile groping it creates the type mGroup variable to apply the next filter or create a temporary variable “mGroup” for further operations.
Annonymous Type selection
As in the code below:
  1: foreach (var items in resultSet)  
  2: {  
  3: Console.WriteLine("{0} - {1}", items.Provider, items.ModelName.Count());  
  4: Console.WriteLine("------------------------------------------------");  
  5: foreach (var item in items.ModelName)  
  6: {  
  7: Console.WriteLine(item.Provider + "\t" + item.ModelName + "\t\t" + item.ModelNumber.Trim() + "\t" + item.MemoryCard);  
  8: }  
  9: Console.WriteLine();  
 10: }  
 11: Console.ReadLine();  
 12: 

Please have a look at the output as shown in the following image:
group by provider in Link
Let Keyword


The Let keyword permits you to store the result of the query that can be used further in subsequent queries.
It creates a new variable and initializes it with the result of the expression and can be used further in queries just the opposite of the Into keyword, which means you created a new variable and you also can use the previous variable so you can use both in the further operations.


  1: var resultSetLet = (from mobile in objMobileCollection  
  2: group mobile by new { mobile.Provider } into mGroup  
  3: //orderby mGroup.Key.Provider,mGroup.Key.MemoryCard
  4: let avgMemory = mGroup.Sum(x => x.MemoryCard) / mGroup.Count()  
  5: where avgMemory > 11  
  6: select new
  7: {  
  8: Provider = mGroup.GroupBy(x => x.Provider),  
  9: ModelName = mGroup.OrderBy(m => m.ModelName),  
 10: ModelNumber = mGroup.OrderBy(x => x.ModelNumber)  
 11: //MemoryCard = mGroup.OrderBy(x => x.MemoryCard),
 12: }).ToList();  
 13: 

Kindly refer to the image shown below for further reference:
Group by is declared with provider value in Link
Please have a look at the complete code shown below:
  1: var resultSetLet = (from mobile in objMobileCollection  
  2: group mobile by new { mobile.Provider } into mGroup  
  3: //orderby mGroup.Key.Provider,mGroup.Key.MemoryCard
  4: let avgMemory = mGroup.Sum(x => x.MemoryCard) / mGroup.Count()  
  5: where avgMemory > 11  
  6: select new
  7: {  
  8: Provider = mGroup.GroupBy(x => x.Provider),  
  9: ModelName = mGroup.OrderBy(m => m.ModelName),  
 10: ModelNumber = mGroup.OrderBy(x => x.ModelNumber)  
 11: //MemoryCard = mGroup.OrderBy(x => x.MemoryCard),
 12: }).ToList();  
 13: 
 14: foreach (var items in resultSetLet)  
 15: {  
 16: Console.WriteLine("{0} - {1}", items.Provider, items.ModelNumber.Count());  
 17: Console.WriteLine("------------------------------------------------");  
 18: foreach (var item in items.ModelNumber)  
 19: {  
 20: Console.WriteLine(item.Provider + "\t" + item.ModelName + "\t\t" + item.ModelNumber + "\t" + item.MemoryCard);  
 21: }  
 22: Console.WriteLine();  
 23: }  
 24: Console.ReadLine();  

 
Please have a look at the output as shown below in the image:


Let Keyword in link


Note: Group by multiple columns in LINQ to SQL as shown in the image below:


multiple keys on group by clasue

This is the complete code used in this article.


  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: 
  6: namespace LINQ_LetKeyword
  7: {
  8:     #region hiddencode
  9:     //class Employee
 10:     //{
 11:     //    public string Name { get; set; }
 12:     //    public string EmpID { get; set; }
 13:     //    public int Salary { get; set; }
 14: 
 15:     //}
 16:     #endregion
 17: 
 18:     class Mobile
 19:     {
 20:         public string Provider { get; set; }
 21:         public string ModelName { get; set; }
 22:         public string ModelNumber { get; set; }
 23:         public int MemoryCard { get; set; }
 24:     }
 25: 
 26:     class Program
 27:     {
 28:         static void Main(string[] args)
 29:         {
 30: 
 31:             
 32: 
 33:             List<Mobile> objMobileCollection = new List<Mobile> { 
 34:              new Mobile{Provider="Apple",ModelName="IPhone3",ModelNumber="I100",MemoryCard=4},
 35:              new Mobile{Provider="Apple",ModelName="IPhone4",ModelNumber="I101",MemoryCard=8},
 36:              new Mobile{Provider="Apple",ModelName="IPhone4S",ModelNumber="I102",MemoryCard=16},
 37:              new Mobile{Provider="Apple",ModelName="IPhone5",ModelNumber="I103",MemoryCard=32},
 38:              new Mobile{Provider="Samsung",ModelName="GalaxyS",ModelNumber="S001",MemoryCard=4},
 39:              new Mobile{Provider="Samsung",ModelName="GalaxyS2",ModelNumber="S002",MemoryCard=16},
 40:              new Mobile{Provider="Samsung",ModelName="GalaxyS3",ModelNumber="S003",MemoryCard=20},
 41:              new Mobile{Provider="Samsung",ModelName="Grand",ModelNumber="G001",MemoryCard=4},
 42:              new Mobile{Provider="Nokia",ModelName="LUMIA530",ModelNumber="N1",MemoryCard=8},
 43:              new Mobile{Provider="Nokia",ModelName="LUMIA730",ModelNumber="N2",MemoryCard=16},
 44:              new Mobile{Provider="Nokia",ModelName="LUMIA930",ModelNumber="N3",MemoryCard=20},
 45: 
 46:             };
 47: 
 48: 
 49:             var resultSet = from mobile in objMobileCollection
 50:                             group mobile by new { mobile.Provider, mobile.MemoryCard } into mGroup
 51:                             orderby mGroup.Key.Provider
 52:                             select new
 53:                             {
 54:                                 Provider = mGroup.Key.Provider,
 55:                                 ModelName = mGroup.OrderBy(x => x.ModelName),
 56:                                 //ModelNumber = mGroup.OrderBy(x => x.ModelNumber),
 57:                                 //MemoryCard = mGroup.OrderBy(x => x.MemoryCard),
 58:                             };
 59: 
 60:             foreach (var items in resultSet)
 61:             {
 62:                 Console.WriteLine("{0} - {1}", items.Provider, items.ModelName.Count());
 63:                 Console.WriteLine("------------------------------------------------");
 64:                 foreach (var item in items.ModelName)
 65:                 {
 66:                     Console.WriteLine(item.Provider + "\t" + item.ModelName + "\t\t" + item.ModelNumber.Trim() + "\t" + item.MemoryCard);
 67:                 }
 68:                 Console.WriteLine();
 69:             }
 70:             Console.ReadLine();
 71: 
 72: 
 73:             /////////////Var Keyword uses
 74: 
 75: 
 76:             //var resultSetLet = (from mobile in objMobileCollection
 77:             //                    group mobile by new { mobile.Provider } into mGroup
 78:             //                    //orderby mGroup.Key.Provider,mGroup.Key.MemoryCard
 79:             //                    let avgMemory = mGroup.Sum(x => x.MemoryCard) / mGroup.Count()
 80:             //                    where avgMemory > 11
 81:             //                    select new
 82:             //                    {
 83:             //                        Provider = mGroup.GroupBy(x => x.Provider),
 84:             //                        ModelName = mGroup.OrderBy(m => m.ModelName),
 85:             //                        ModelNumber = mGroup.OrderBy(x => x.ModelNumber)
 86:             //                        //MemoryCard = mGroup.OrderBy(x => x.MemoryCard),
 87:             //                    }).ToList();
 88:             
 89:             //foreach (var items in resultSetLet)
 90:             //{
 91:             //    Console.WriteLine("{0} - {1}", items.Provider, items.ModelNumber.Count());
 92:             //    Console.WriteLine("------------------------------------------------");
 93:             //    foreach (var item in items.ModelNumber)
 94:             //    {
 95:             //        Console.WriteLine(item.Provider + "\t" + item.ModelName + "\t\t" + item.ModelNumber + "\t" + item.MemoryCard);
 96:             //    }
 97:             //    Console.WriteLine();
 98:             //}
 99:             //Console.ReadLine();
100:             //var objresult = from emp in objEmployee
101:             //                let totalSalary = objEmployee.Sum(sal => sal.Salary)
102:             //                let avgSalary = totalSalary / 5
103:             //                where avgSalary > emp.Salary
104:             //                select emp;
105: 
106:             
107:         }
108:     }
109: }
110: 

I wish it will help you utilize both features at the best.
To learn more about MVC please go to the following link.


MVC Articles


Thanks.
Enjoy coding and reading.

Tuesday, August 26, 2014

Difference between IEnumerable and IEnumerator

Difference between IEnumerable and IEnumerator

Hi Geeks,

 

Dotnetpiper

 

Here are few points which I learnt about IEnumerable and IEnumerator.

  1. IEnumerable uses IEnumerator internally.
  2. IEnumerable doesnt know which item/object is executing.
  3. Whenever we pass IEnumerator to another function ,it knows the current position of item/object.
  4. Whenever we pass IEnumerable collection to another function ,it doesn't know the current position of item/object(doesn't know where I am)
  5. IEnumerable have one method GetEnumerator()

IEnumerator have one Property current and two methods Reset and MoveNext.

In simple words: If you want to loop through with the collection one by one and you are not interested in the current cursor position then should opt 

Enumerable.Because code is simple and short.

And if you are keen to know the current position of object then should go for IEnumerate.

 

To know more about MVC please go through with given below link.


MVC Articles


Enjoy Coding and Reading Smile

Friday, August 22, 2014

Difference between prop and attr in JQuery.

Difference between prop and attr in JQuery?
Answer:

Jquery


JQuery.attr()
Get the value of an attribute for the first element in the set of matched elements.
Whereas:
JQuery. Prop ()
Gets the value of a property for the first element in the set of matched elements.


What Attributes actually are
Attributes carry additional information about an HTML element and come in name=”value” pairs. You can set an attribute for a HTML element and define it when writing the source code.
For example:
<input id="txtBox" value="Jquery" type="text" readonly="readonly" />
As shown above, “id”, "type” and “value" are attributes of the input elements.

Property

Property is a representation of an attribute in the HTML DOM tree. Once the browser parses your HTML code, the corresponding DOM node will be created that is an object thus having properties.
In the above case, once the browser renders the input in the browser, other properties like align, alt, autofocus and baseURI are checked and so on, will be added as depicted in the following image.
clip_image001


Since attr() gives you the value of an element as it was defined in the HTML on page load. It is always recommended to use prop() to get the values of elements modified via JavaScript/jQuery in the browser at runtime. It always keeps the current state value.
Here we'll have a look at the example that also states the difference between both of them.
I have a HTML text box with some attributes as shown below:


clip_image002


If I run the following jQuery syntax then it will produce such results.


clip_image003


Now I've slightly changed the code and removed the read-only attribute as shown below in the image:


clip_image004


I run the application and see some attribute and property to understand the difference on fly.
Initially after running the application we have these attributes and properties of input text type as depicted in the image below.
Note: Kindly scroll down when you run the attached sample application to see the Value property using the Firebug tool of the Firefox browser.
clip_image005


Now I changed the value at runtime and see the attributes and properties. I've put Welcome jQuery in the textbox. Now see that the attribute value is still jQuery while the value property has been changed to Welcome JQuery.


clip_image006


The property always represents the current state while the attribute (except in old versions of IE) represents the initial state or is meant for HTML attributes since they are strictly defined. The attribute tells you nothing about the current state.

Reference MSDN:

for a checkbox (jquery 1.6+)
<input id="check1" checked="checked" type="checkbox" />
.attr('checked') //returns checked
.prop('checked') //returns true
.is(':checked') //returns true


Prop() method returns Boolean value for checked, selected, disabled, readOnly..and so on while attr returns defined string. So, you can directly use .prop("checked") in if condition.
SelectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected..and so on should be retrieved and set with the .prop() method. These do not have corresponding attributes and are only properties.
.attr() calls .prop() internally so .attr() method will be slightly slower than accessing them directly through .prop().


Question: What is the difference between .js and .min.js and vsdoc.js?


Answer: The jQuery library comes in the 2 versions Production and Deployment. The deployment version is also known as the minified version. So .min.js is basically the minified version of the jQuery library file. Both the files are the same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.


clip_image007
Question: How to select id that contains Meta Character.
Answer: If any element id (<li id="first-li" class="list">Sachin Kalia</li>) contains a meta character between the id then it should be resolved using the two backslashes (\\) as the prefix in the ID selector.
clip_image008


Thanks.

To learn more about MVC please go to the following link.


MVC Articles

Thanks

Enjoy Coding and ReadingSmile

Tuesday, August 12, 2014

Cross-Site Scripting Attack in MVC4

Cross-Site Scripting Attack in MVC4

 

threats

 

In this article we will explore Cross-Site Scripting in an MVC application. In general this is the most dangerous threat by hackers.


Cross-Site Scripting is a kind of security feat. An attacker inserts malicious code into a web page or a storage database. XSS in itself is a threat that is brought by the internet security weaknesses of client-side scripting languages.
There are certain scenarios where it could fit like: If an attacker posts a malicious script that he can cause the browser to execute, this script is executed in the context of the victim's session, essentially enabling the attacker to do anything he wants to the DOM, including showing fake login dialogs or stealing a cookie.
There could be various ways to inject malicious code such as:

  • Malicious Attack with login Dialog
  • Vulnerable code segment inserted
  • Query String Message
  • HTML markup Passed in TextBox

Here I have created a MVC application and tried to insert some encoded HTML as shown in the image below.
Kindly hit the following URL : http://localhost:64175/Xss/Create



As soon as I click on the create button it shows in yellow an error screen as depicted in the image below:



MVC is smart enough to deal with such threats and prevents cross site attacks, this is one advantage of MVC because in case you forgot to handle this.
In case you want the user to submit HTML markups in the address then you can disable this prevention using [ValidateInput(false)].



This allows you to store values to the database using Entity Framework.
Now the output will be like this due to by default Razor will encode the HTML markups.



To convert HTML encoded to markup use the @Html.Raw helper method. Refer to the image shown below.



Now the output will be like this. Hit the following URL: http://localhost:64175/Xss/EmpDetails



Until here we have almost disabled all the security points and are about to enter a highly vulnerable string and a possible way to hack a document cookie and alert.


<img onmouseover=alert(1) src="/Images/Clickme.jpg" onmouseout=alert(document.cookie) >



As soon as you click it prompts you with an alert as shown below:


To prevent this use the Microsoft Anti-Cross Site Scripting Library (AntiXSS) and set it as your default HTML encoder.
How do you prevent XSS? Use of the following rules strictly will help prevent most if not all XSS attacks in your application:

  1. Ensure all of your output is HTML-encoded.
  2. Don't allow user-supplied text to end up in any HTML element attribute string.
  3. Prevent the use of Internet Explorer 6 by your application by checking Request.Browser as outlined at msdn.microsoft.com/library/3yekbd5b.
  4. Understand your control's behaviour and whether it HTML encodes its output. If it doesn't, encode the data going to the control.
  5. Use the Microsoft Anti-Cross Site Scripting Library (AntiXSS) and set it as your default HTML encoder.
  6. Use the AntiXSS Sanitizer object (this library is a separate download and is addressed later in this article) to call GetSafeHtml or GetSafeHtmlFragment before saving HTML data to the database; don't encode the data before saving.

Kindly find a source code for XSS. You can also visit DotnetPiper.com to understand more about MVC and jQuery.
Note: select all SimpleMemberShip and unzip into single Extract to SimpleMemberShip.
Please replace the packages and bin folder to SimpleMemberShip after unzipping. Refer to the image below:

Download code from here

Cross-Site Scripting Attack in MVC4


To learn more about MVC please go to the following link.
MVC Articles

Thanks


Enjoy Coding and ReadingSmile

Monday, August 11, 2014

Validation failed for one or more entities. See EntityValidationErrors property for more details.
Error-Messages
Today I encountered an error during data insertion through Entity Framework as per the Title.
There could be a various cause of such issue .Here I am talking about one of them.In database I restricted Name column data Type to nvarchar(10).
 and I was inserting value which has more than 10 character.
 
image
 
As soon as I try to insert value it generates me an error as depicted below:
 
clip_image002
.
 
I have used the code as shown below to identify the root cause.
  1: public ActionResult Create(EmpRegistration collection)
  2:         {
  3:             try
  4:             {
  5:                
  6:             }
  7:             catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
  8:             {
  9:                 Exception raise = dbEx;
 10:                 foreach (var validationErrors in dbEx.EntityValidationErrors)
 11:                 {
 12:                     foreach (var validationError in validationErrors.ValidationErrors)
 13:                     {
 14:                         string message = string.Format("{0}:{1}",
 15:                             validationErrors.Entry.Entity.ToString(),
 16:                             validationError.ErrorMessage);
 17:                         // raise a new exception nesting
 18:                         // the current instance as InnerException
 19:                         raise = new InvalidOperationException(message, raise);
 20:                     }
 21:                 }
 22:                 throw raise;
 23:             }
 24:         }

This code  help you to trace exact error.The way it suggested to me that “The field Name must be a string or array type with a maximum length of '10'.”



image



This is the complete code which runs perfectly as shown below .I wish this code will help you sometime.


  1: public ActionResult Create(EmpRegistration collection)
  2:         {
  3:             try
  4:             {
  5:                 if (ModelState.IsValid)
  6:                 {
  7:                     EmpRegistration empRegis = new EmpRegistration();
  8:                     // TODO: Add insert logic here
  9:                     empRegis.Address = collection.Address;
 10:                     empRegis.City = collection.City;
 11:                     empRegis.Id = 7;
 12:                     empRegis.Name = collection.Name;
 13:                     objEnity.EmpRegistrations.Add(empRegis);
 14:                     objEnity.SaveChanges();
 15: 
 16:                     return View();
 17:                 }
 18:                 return View(objEnity.EmpRegistrations);
 19:             }
 20:             catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
 21:             {
 22:                 Exception raise = dbEx;
 23:                 foreach (var validationErrors in dbEx.EntityValidationErrors)
 24:                 {
 25:                     foreach (var validationError in validationErrors.ValidationErrors)
 26:                     {
 27:                         string message = string.Format("{0}:{1}",
 28:                             validationErrors.Entry.Entity.ToString(),
 29:                             validationError.ErrorMessage);
 30:                         // raise a new exception nesting
 31:                         // the current instance as InnerException
 32:                         raise = new InvalidOperationException(message, raise);
 33:                     }
 34:                 }
 35:                 throw raise;
 36:             }
 37:         }

To learn more about MVC please go through the following link.
MVC Articles
Enjoy coding and readingSmile

Friday, August 8, 2014

Difference/Similarities BETWEEN HTML.RENDERACTION AND HTML.ACTION

 

image

Html.RenderAction() and Html.Action()  are action helper methods in ASP.NET MVC. Generally both methods are used for calling action methods or child action methods  and rendering the result of action method in view.

@Html.Action() – Invokes the specified child action method and returns the result as an HTML string.

The way to call action via RenderAction is shown below:

  1: e.g. @Html.Action("ChildAction", "Home", new { param = "first" })

 

This method result can be stored in a variable, since it returns string type value.Kindly look at the image shown below:

image

 

@{ Html.RenderAction() – Invokes the specified child action method and renders the result inline in the parent view.

This method is more efficient if the action returns a large amount of HTML.

The way to call action via RenderAction is shown below:

  1: @{Html.RenderAction("ChildAction", "Home",new { param = "first" });}

It returns Voids and render/give result directly to the response .

 

image 


Both methodsis also used for rendering the partial view using Child Action


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.

This method is faster than Action method since its result is directly written to the HTTP response stream.

Thanks

To learn more about MVC please go through the following link.

MVC Articles

Enjoy coding and readingSmile

Thursday, August 7, 2014

  • The RouteData must contain an item named "action" with a non-empty string value
Trouble-Shooting
Hi Folks,

Since I am exploring MVC these days I have tried to temper MVC with given functionality and encountered an error. I think we should understand why it comes and what exactly is wrong with our code.
Errors
  • Value cannot be null or empty. Parameter name: controllerName
  • The RouteData must contain an item named "action" with a non-empty string value

First: Value cannot be null or empty. Parameter name: controllerName.
I changed the route map collection of the application slightly and kept the controller value blank as shown in the image below:
Method for Registering Routes

Because on each URL hit, it first goes to the Route collection and finds a controller to invoke an action method. When it doesn't find a controller value, it issues such an error.

Second: The RouteData must contain an item named 'action' with a non-empty string value.
I changed the route map collection property of the application slightly and kept the action value blank as shown in the image below:


RouteData Error
New RegisterRoute Method

Because on each URL hit, it first goes to the Route collection and finds a controller to invoke an action method. When it doesn't find an action method name, it issues such an error.
The solution for both the errors is, please set some real value for both of the parameters to run an application expected.
For example I have given the value ” Home1” as the controller name but it doesn't exist in my application, so you may encounter a page 404 not found error as depicted in the image below:

Update in Register Route
Page Not Found Error


I hope that if you confront such an issue then this article will be helpful.

Note: The scenarios mentioned above are some of the possible causes of such an error.
Thanks. To learn more about MVC please go through the following link.
MVC Articles
Enjoy coding and reading

Wednesday, August 6, 2014

Child Action Methods in ASP.NET MVC4

Child Action Methods in ASP.NET MVC4

 

ChildAction

 

In this article we will explore Child Action method which is accessible at View level. In general each public method in a controller class is an action method.

There could be multiple scenarios when we want to display some dynamic information (data) on pages. Child action is helpful in those scenarios.

ChildAction method is somewhere an action method thought its accessible from View only, if you invoked this action via URL then it prompts you an error which we will look down the level in this article.

I have a HomeController in MVC application which contains a code as given below:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using System.Web.Mvc;
  6: using FiltersDemo.Controllers.CustomFilters;
  7: 
  8: 
  9: namespace FiltersDemo.Controllers
 10: {
 11:     public class HomeController : Controller
 12:     {
 13:         #region Commented
 14:         //[CustomAuthorization]
 15:         //[CustomAction]
 16:         //[CustomResultAttribute]
 17:         //[CustomExceptionAttribute]
 18:         #endregion Commented
 19: 
 20:         public ActionResult Index()
 21:         {
 22:             
 23:            
 24:             ViewBag.TempValue = "Index Action called at HomeController";
 25:             return View();
 26:         }
 27: 
 28:         [ChildActionOnly]
 29:         public ActionResult ChildAction(string param)
 30:         {
 31:             ViewBag.Message = "Child Action called. "+ param;
 32:             return View();
 33:         }
 34: 
 35:     }
 36: }
 37: 
 38: 


 


To behave an action as child action it requires decorating with [ChildActionOnly] as shown in image below:


 

clip_image002

Initially it is invoking to Index action which in turn returning to Index views, and at View level it calls to ChildAction named as “ChildAction”.

This is the code of index.cshtml as shown below:

  1: @{
  2:     ViewBag.Title = "Index";
  3: }
  4: <h2>
  5: Index</h2>
  6: <!DOCTYPE html>
  7: <html>
  8: <head>
  9:     <title>Error</title>
 10: </head>
 11: <body>
 12:     <ul>
 13:        <li>
 14:             @ViewBag.TempValue
 15:         </li>
 16:         <li>@ViewBag.OnExceptionError</li>
 17:        
 18:         @*<li>@{Html.RenderAction("ChildAction", new { param = "first" });}</li>@**@
 19:         @Html.Action("ChildAction", "Home", new { param= "first" })
 20: 
 21:     </ul>
 22: </body>
 23: </html>
 24: 
And this is how we declare an action in view as depicted in image below:

clip_image004

Now I run application and it will call an action method via Index.cshtml page. And result is as below:

clip_image007clip_image005

Note: if you try to access ChildAction method directly than it prompts you an error as per image depicted below.

Copy this URL and paste it to browser => http://localhost:50255/Home/ChildAction/Second

It prompts you an error:

clip_image009

It may help you sometime in upcoming time.

Thanks

To know more about MVC please go through with given below link.

MVC Articles
Enjoy Coding and Reading clip_image010