Steph
Steph

Reputation: 167

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?

Upvotes: 8

Views: 6104

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 8

Related Questions