Declare functions or method in a view - c#

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?

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.

Related

Getting Error in using user control(.ascx) on asp.net mvc layout page

I am integrating Asp.net User control(.ascx) in my Mvc Layout page i.e is master page and i am using razor engine.
Error:Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper ascx.
Control '1_hdfData' of type 'HiddenField' must be placed inside a form tag with runat=server.
This is my code:
_Layout.cshtml:
#Html.Partial("~/UserControls/Data.ascx")
Data.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Data.ascx.cs" Inherits="MyNameSpace.Data" %>
<asp:HiddenField ID="hdfData" runat="server" />
--Rest all other asp.net server side controls---.
Data.ascx.cs:
namespace MyNameSpace.Data
{
public partial class Data : ViewUserControl
{
//Page_Load events and other code
}
}
Is it like if i am inheriting User Control(.ascx) from ViewUserControl so i cant use asp.net control?
Can anybody help me with this?
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Data.ascx.cs" Inherits="MyNameSpace.Data" %>
<form runat="server">
<asp:HiddenField ID="hdfData" runat="server" />
--Rest all other asp.net server side controls---.
</form>
I am sharing one idea, but it's not good practice.
#Html.Partial("_ASCX_FILE")
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%# Register Assembly="SomeAssembly" Namespace="SomeNs" TagName="ASCX_FILE" %>
<ASCX_FILE:SomeControl runat="server" ID="fooControl" />
Possibly above solution can sort out your issue.
Suggesting again, try using pure MVC flavor. :)

How to view HTML file in Partial View of ASP.NET MVC (not Razor)

I have an application in which I have created a partial view as below:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
and my parent view has the following code:
<div>
<% #Html.RenderPartial("ViewerControl"); %>
</div>
Now, I want to open an HTML file in the partial view. I am not sure how to do it. Quick sample code will be highly appreciated.
Views do not support server side include directives or similar. Your best bet would be to create an action result that returns the markup as a ContentResult.
public ContentResult HtmlFile() {
return Content(File.ReadAllText(Server.MapPath("Give the path here")));
}
Then in your view:
<%: Html.Raw(Html.Action("HtmlFile")) %>
Totally off the cuff, but you get the point: invoke a server side action to retrieve your markup, or alternatively deliver it via the Model on the previous Action Result execution.

C# .NET include file

I searched a way to include a file in a web application (like a menu, so I won't have to edit it on all pages when applying changes), but haven't found something as simple as
<?php include "Menu.html"; ?>
Can you please help?
Have you looked into Master Pages? They would certainly help you add the same layout across several pages.
Or perhaps you want a reusable User Control (that you write yourself)?
We don't use "include page" in asp.net, even though it is possible (with a different syntax of course). Instead, have a look at Master page concept.
MasterPages allow you to maintain a parent/child relationship between a master page which contains content that wraps around any number of child content pages.
Similarly, UserControls allow you to re-use whatever content you want on whatever page you want, whether it's a MasterPage or ContentPage:
<%# Page Language="C#" %>
<%# Register TagPrefix="uc" TagName="Spinner"
Src="~/Controls/Spinner.ascx" %>
<html>
<body>
<form runat="server">
<uc:Spinner id="Spinner1"
runat="server"
MinValue="1"
MaxValue="10" />
</form>
</body>
Methods (C#)
Executable code:
Page include
<!--#include file="a.aspx"-->
Execute independently inside a page
<% Server.Execute("a.aspx"); %>
Non-executable code:
<% Response.WriteFile("a.inc"); %>
I believe this is what you are looking for.
<!--#include file="wisdom.aspx"-->
I use C#.net
<% Response.WriteFile("YourPage.aspx"); %>
and this works real well for me!!
I also use your line,
<!--#include file="wisdom.aspx"-->
when I am in HTML mode.

From UserControl to parent master page

I have a weird scenario but this was how it was designed before me. Basically I have userControl, and there is a child.masterpage
in the userControl in the ascx file it contains the following
<div><%=_template%></div>
the child.masterpage inherits from a parent.masterpage, in the child.masterpage there is a call to the userControl
<asp:Content><ucc:UserControl></ucc>
the parent.masterpage has other fields in it and it has a .cs file with a c# function
public void passVal(string s)
Now what I want to do is to pass a value from the user control directly to the parent.masterpage function so that I can put it in the parent.masterpage literal I have created.
How can I achieve this (again, this is existing design and I cant turn things around) I am just adding a functionality.
<%# Master Language="C#" AutoEventWireup="true" MasterPageFile="../common/main.master" %>
<%# Register Src="UserControl.ascx" TagName="Ord" TagPrefix="uc" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<div class="in"><uc:OrderReceipt ID="myord" runat="server" Visible="true"/>
<div style="margin-bottom:30px;">
Back to Home Page
</div>
</asp:Content>
You can use the Page.Master property to get a hold of the master page instance.
protected someEvent(object sender, EventArgs e)
{
(Page.Master as ChildMaster).passVal("some string");
}
More of an Answer:
I was just reviewing your OP and realized something. The code that kept puzzling me was the user control.
in the userControl in the ascx file it
contains the following
<div><%=_template%></div>
I haven't seen the code behind but my guess is that the user control is simply used to output dynamic HTML. I bet if you looked at the code behind (.cs file) of the user control, you would find a variable called _template. It is a string variable that is pumped with html at run time.
Now, that doesn't answer your question but, if you didn't already know that ... it is good to know =P
Now, the next mystery is the one concerning your missing code behind file for the child master page.
My theory is that whoever made it did it with some error that would cause it not to automatically generate a code behind file. Or, they made it from scratch and just simply added it to the project but neglected to make a code behind as well.
I made a master page, then made another one called child. I am able to subclass it and here is what the markup and code behind look like.
<%# Master Language="C#" MasterPageFile="~/Master.master" AutoEventWireup="true" CodeFile="Child.master.cs" Inherits="Child" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
</asp:Content>
public partial class Child : Master
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
In comparing the markup to yours, the key difference here is that mine explicitly mentions a CodeFile attribute.
Create a new cs file and following the naming convention. Then add the CodeFile and Inherits attributes to your child master page. This should wire everything up correctly and allow you to start adding methods and such to the child master page.
Let me know where you are at and we'll take it from there. GL

What is the easiest (correct) way in ASP.NET MVC 2 to make a button-click display text?

I need to make a quick demo showing how to do interactivity on an ASP.NET MVC page.
I opened an ASP.NET MVC project in Visual Studio 2010, put the view in design mode, dragged in a button, double-clicked on it and looked at the view again. I was expecting to see some ingenious JQuery code generated but instead an <asp:Button> and a <script runat="server"> block was created, which seems to be a mixing of classic ASP.NET and ASP.NET MVC metaphors. I don't think that is the recommended way to build interactivity in MVC, right?
So what is the easiest, most standard-MVC approach for me to (1) create a button, (2) when the button is clicked, change some text in my view?
is it really best practice in MVC to use the runat-server block?
are there some easy wizards which generate JQuery interactivity so that I can do this in a best-practice MVC way?
or do I need to implement the JQuery myself as I would on a plain HTML page without ASP.NET MVC?
View:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
}
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server">
<h2><%: ViewData["Message"] %></h2>
<p>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</p>
</form>
</asp:Content>
You should not use asp.net ajax controls in asp.net MVC.
If you want to create a button just write some old-fashioned html like:
<input type="button">Button</input>
then if you need this button to make some action, just write new action instead of code behind method like and call it like:
<input type="button" onclick="javascript:window.location = 'http://mypage.com/mycontroller/buttonaction' />
or even better create a link instead of button by using mvc builded-in html helpers:
<%= Html.ActionLink("Do something" ,"ButtonAction") %>
Faster you catch it better for you. You need to resign from asp.net ajax habit. There is no postback or code behind and it's removed with a reason. MVC is controlled by executed actions which means that you are steering the application by calling specified links. By using pure html you've got lot more control on your output code and flow of actions in your application.
Remember that MVC is not a new ASP.NET AJAX and those two will goes together, so if this style of writing we apps does not suits you then you do not need to use it. It's just the metter of choice which technology is better for you and your projects.
Also to learn more about mvc visit asp.net mvc webpage. I specially recomend you to see some videos like this one. It will definitely help you to better understand what mvc is and what are it's advantages and disadvantages.

Categories

Resources