.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> General >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Using multiple functions within a single controller for a single view, in ASP.Net MVC.

Posted By:ASPEvil       Posted Date: August 31, 2014    Points: 200    Category: General    URL: http://www.dotnetspark.com  

Intro:- How we can use multiple functions for using them for a single View.
 

In ASP.Net MVC, we know, by default, every View is having its associated code within its associated controller file. For example: the Index View is having the following default code for it:-
-----------------------------------------

[vb.net code]

Function Index() As ActionResult
        ViewData("Message") = "Welcome to ASP.NET MVC!"

        Return View()
End Function
[c# code]

ActionResult Index() {
        ViewData("Message") = "Welcome to ASP.NET MVC!";

 return View();
 }
-------------------------

Now, all the coding work we need to do, we can do it within the above mentioned coding blocks. But in case, if we do not want to write our code directly inside these above mentioned coding blocks, instead we want to make our coding work in separate functions, then how we can do this? This article shows you how.

Assume that, we are having a separate function as follows:-

-----------------------------------
[vb.net code]

Function hello() As String
        Dim str As String = "Hello World"
        Return str
    End Function

[c# code]

string hello() {
        string str = " Hello World ";
        return str;
    }

-----------------------------------

The above function declares a string which is named as: "str" and then assigns the value: "Hello World" to it.

Now lets see how we can use this function with our Index view, as follows:-

---------------------
[vb.net code]

Function Index() As ActionResult
        ViewData("Message") = "Welcome to ASP.NET MVC!"

        ViewData("hw") = hello()

        Return View()
    End Function

[c# code]

ActionResult Index() {
        ViewData("Message") = "Welcome to ASP.NET MVC!";

        ViewData("hw ") = hello();

        return View();
    }
------------------------


The above code is almost same as the default code for the Index view, except the line:  ViewData("hw") = hello()
 Or ViewData("hw") = hello(); This particular line of code directly assigns the return value of the function: "hello", to the ViewData("hw"), so if we use the ViewData("hw") with your Index View, then it will show the value of the hello() function there.



Thanks.