Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare functions or method in a view

Since there is no more code behind in .aspx pages in .NET MVC, It seems impossible to declare a function or method direclty in the .aspx page (the view).

In classic ASP, I could add a script tag with runat="server" to declare a local function.

Each client has its own view. The method in the controller send the right view to the right client.

What I'd like to do is to change some method logic depending of the client. Since this is highly dynamic,I don't want to add a class or a method in the controller then rebuild and upload in production each time we have a new client.

So I thought of adding some logic directly in the view. Is this possible?

like image 213
Steph Avatar asked Dec 02 '11 14:12

Steph


People also ask

How do you declare a function?

Function Declarations The actual body of the function can be defined separately. int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Can we use view inside function?

You won't be able to create a view inside a function (msdn.microsoft.com/en-gb/library/ms191320.aspx). To do so inside a stored procedure you will need to use dynamic SQL. stackoverflow.com/questions/7712702/… WHY do you need a function to create the view?!?!?

What is function declaration example?

For example, if the my_function() function, discussed in the previous section, requires two integer parameters, the declaration could be expressed as follows: return_type my_function(int x, y); where int x, y indicates that the function requires two parameters, both of which are integers.

How do you write a function in razor view?

If you want to write a function, you can't just open new @{ } razor block and write it there… it won't work. Instead, you should specify @functions { } so that inside the brackets you will write your own C#/VB.NET functions/methods. This code will print the numbers from 1 to 10: Number 1.


1 Answers

In classic ASP, I could add a script tag with runat="server" to declare a local function.

I guess you mean in classic WebForms, because in classic ASP the runat="server" attribute doesn't exist.

So you could do the same in an ASP.NET MVC view using the WebForm view engine:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <script runat="server" type="text/C#">
        public string Foo()
        {
            return "bar";
        }
    </script>

    <div><%= Foo() %></div>

</asp:Content>

Now whether this is a good idea and if you should do it is an entirely different topic.

like image 157
Darin Dimitrov Avatar answered Sep 20 '22 17:09

Darin Dimitrov