What is the PROPER way to create an ASPX View in MVC? - c#

Essentially, my issue is this: I'm trying to display a ViewData variable on an ASPX page, but I'm getting "ViewData does not exist in the current context."
What led me here? I'm new to MVC, and am following an online tutorial. In Lesson 1, he has us create a view by going to Add > View, which creates a Razor view. Then, in the next tutorial, he's teaching us to use ViewData to pass a variable to the view. But, when he displays it, he's doing so using the <%: %> method, which doesn't work on my Razor page. So, I try to create an ASPX page in my View folder by creating a Web Form the traditional way. When I do that, I get the error mentioned above. I have successfully figured out how to get the Razor method working in my cshtml page, but what is the appropriate method should I want to do it the "angle bracket - percent" way?
Edit: Basically, all I did was follow the instructions for Tutorial 2 in the following walk-through. He doesn't really explain HOW he created the ASPX page (or that he used an ASPX page at all). If anyone knows of a better tutorial that's more complete, I'm all ears.
http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in#Lab1:- Creating a simple hello world ASP.NET MVC Application
Edit2: By request, here's my code:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MVCLearn.Views.FirstMVC.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= ViewData["vwTest"] %>
</div>
</form>
</body>
</html>
And here is my Controller:
public class FirstMVCController : Controller
{
// GET: FirstMVC
public ActionResult Index()
{
ViewData["vwtest"] = "Something";
return View();
}
public ActionResult SayHello()
{
return View("HelloView");
}
}

<%= ViewData["vwTest"] %>
ViewData["vwtest"] = "Something";
vwTest != vwtest
You should write same name
<%= ViewData["vwTest"] %>
ViewData["vwTest"] = "Something";

Related

How ASP.net is used before Razor was introduced

I am a little confused in how ASP.NET code is written before Razor was introduced. All I can see in many pages on the internet is how Razor is used with ASP.net. I want to know how ASP.net code is been written without Razor.
classic ASP
<html>
<body>
<%
response.write("My first ASP script!")
%>
</body>
</html>
ASP.NET with Razor
<html>
<body>
<h1>Hello Web Pages</h1>
<p>The time is #DateTime.Now</p>
</body>
</html>
ASP.net without Razor???
basically I want to know how people coded in ASP.net (not classic ASP) before razor was introduced.
Classic ASP is usually written with <%= %> tags, not with response.write(). Example:
<html>
<body>
<%= "My first ASP script!" %>
</body>
</html>
The ASP.NET syntax is very similar, but the <%: %> tag was introduced to automatically HTML encode the values, similar to what Razor does. Example:
<html>
<body>
<h1>Hello Web Pages</h1>
<p>The time is <%: DateTime.Now %></p>
</body>
</html>
For code more complicated than just showing values, you use <% %> tags around server code, just as in classic ASP. Example:
<html>
<body>
<h1>Hello Web Pages</h1>
<% for (int i = 1; i <= 10; i++) { %>
<p>Line <%: i %></p>
<% } %>
</body>
</html>

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.

How to stop asp.net encoding characters before outputing to html?

I have a function that generates a javascript code for me.
<img src="abc.png" alt="hello" onclick="<%: getOnCilckJS(arg) %>" />
c# code
protected String getOnCilckJS(int arg)
{
if (arg==1)
{
return "alert('hello world');";
}
else
{ return "alert('hello universe');";
}
}
all works fine apart from when the page is loaded asp.net converts single quotations ' to the encoded html string (')
How can I avoid this and make ' appear in the html?
Your application is Web Forms or MVC?
If it is MVC, you can try the Html.Raw(...) function, If it is Web Forms you can check this link.
You're using <%: %>, which actually does encode the value. You're looking for <%= %>.
See also Diference between special tags asp.net.
In ASP.NET WebForms the razor syntax is invalid so the way to stop the string encoding in the output of a string is to use the HtmlString() for example the inline syntax is:
<%: new HtmlString(stringVariable) %>
Below is an example how to output a variable in JavaScript inline code on a ASP.NET WebForm page. The code sample outputs a C# string array into a JavaScript array:
<script type="text/javascript">
var array = ["<%: new HtmlString(string.Join(#""",""", stringArray)) %>"];
</script>
Normally, the double quote characters are html encoded and converted as " and breaks the JavaScript syntax - using the HtmlString() method stops the encoding.
However, as stated in previous answer to avoid using the HtmlString() simply use the appropriate special ASP.Net tag syntax to output your values - <%: %> encodes characters and <%= %> is raw output!
Review the differences between ASP.Net special tags here!
Your code working to me :
But just change <%: to <%= ( and I send the parameter myself)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="xxxx.aspx.cs" Inherits="SampleAngularApp.xxxx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
**<img src="abc.png" alt="hello" onclick="<%= getOnCilckJS(11) %>" />**
</div>
</form>
</body>
</html>
Server side
**protected string getOnCilckJS(int arg)**
{
if (arg == 1)
{
return "alert('hello world');";
}
else
{
return "alert('hello universe');";
}
}
I got the alert message without any single quote

Copy placeholder text into a 2nd location

I have an MVC Masterpage.
Within the body, I have a placeholder for a title that all the views using this masterpage populate:
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
But as well as this title being used how it is, I want the exact same text to go in the title section of the head tag.
Of course, I could use another placeholder and make every single view specify the same content twice, but it would be better if some code could magically copy the literal text out of the placeholder and put it into the head title tag as well.
Obviously Javascriptis no use, because google wont process it to the page title. So I need to do this serverside.
In general, you would bind these values in the view to data either on a model or perhaps in a ViewBag (or ViewData for older versions of MVC) or something of that nature. So in your Layout (Master Page? Must be an older version of MVC?) you might have a couple of references to a ViewBag (or ViewData) value. Something like this:
<html>
<head>
<title><%= ViewBag.PageTitle %></title>
</head>
<body>
<div id="somePageTitle"><%= ViewBag.PageTitle %></div>
</body>
</html>
or:
<html>
<head>
<title><%= ViewData["PageTitle"] %></title>
</head>
<body>
<div id="somePageTitle"><%= ViewData["PageTitle"] %></div>
</body>
</html>
Then in your controller you would set that value as needed:
ViewBag.PageTitle = "This is a page title";
or:
ViewData["PageTitle"] = "This is a page title";
That would bind that value to both locations in the view. It's more common to use ViewBag (or other constructs, like ViewData and TempData, often depending on the MVC version being used) for elements in the layout (Master Page) and to use view models for elements in the specific view.
First off David's answer is right
Actual implementation would be whatever.master
<!DOCTYPE html>
<html>
<head>
<title><%= ViewData["Title"] %></title>
</head>
<body>
<asp:ContentPlaceHolder ID="TitleContent" runat="server"/>
</body>
</html>
In your View
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
<%= ViewData["Title"] %>
</asp:Content>
Change it in the controller
public ActionResult Index()
{
ViewData["Title"] = "My new title";
return View();
}
Or set it in the View itself
<script runat="server">
ViewData["Title"] = "My new title";
</script>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
<%= ViewData["Title"] %>
</asp:Content>
Since these are variable, use them anywhere in your page you like
// These are the same
ViewData["Title"] = "My new title";
ViewBag.Title = "My new title";
// These are the same
<%= ViewData["Title"] %>
<%= ViewBag.Title %>
public Dictionary<string, object> ViewData
public dynamic ViewBag // .NET 4.0 +
Thanks for all your help.
I wanted to set the data in the view because I have different controllers using the same view, and also some controllers returning different views depending on the logic, so it made sense to define the page title on the view where it is a known entity, especially since it is usually not model data and is thus always a constant text for that page.
One complication, is that if the view was to be set as a dynamic piece of data taken from the model, that hadn't been calculated yet (such as a deferred execution iqueryable), then the masterpage never realizes the value unless you populate it in the view at a higher point in the page.
In other words, the view has to set the viewdata in script in a content placeholder ABOVE where it will be in the masterpage. You cannot set the viewdata[] property in the body content if the masterpage uses it in the head section.
This works:
<head>
<asp:Placeholder ID="HeadContent" runat="server"/>
<title><%: ViewData["PageTitle"] %></title>
</head>
<body>
<%: ViewData["PageTitle"] %>
</body>
Then in the view you can set the title:
<asp:Content ContentPlaceHolderID="HeadContent" runat="server">
<% ViewData["PageTitle"] = Model.SomeValueThatHasDefferedExecution; %>
</asp:Content>

HTML markup rendering issue in ViewData? Also, MultiView functionality in MVC?

i'm trying to populate a ViewData instance with html markup like shown below. When the page renders, the html tags get rendered as text and not html markup. Anyone know why?
Controller code:
if (user.ActivationStatus == false)
{
...
ViewData["Message"] = "<p>Your account has been activated, you're good to go.</p>";
}
else
{
ViewData["Message"] = "<p>Sorry, this account has already been activated.</p>";
}
return View();
View code:
<h2>Confirmation</h2>
<p><%: ViewData["Message"] %></p>
Secondly, I have used the MultiView feature in asp.net webforms in the past. This functionality is ideal and like to implement a similar functionality in MVC.
Is there any way i can call different PartialViews dependant on the function outcome(like the 'if' statement above) from controller code to a placeholder in the View?
<%: %> == Html.Encode(ViewData["Message"]);is HTML Encoding your string...
Try this:
<%= ViewData["Message"]%>
Also, you should be able to control Partial Controls using ViewData and depending on the values in ViewData you could render different partials. You could also strongly type your view to a model that represents the behavior your after on the page...
You can create an MvcHtmlString
<%: MvcHtmlString.Create(ViewData["Message"]) %>
But really you should not have the html in your controller.
By making your view strongly-typed you could instead do something like this.
<h2>Confirmation</h2>
<% if(Model.ActivationStatus) { %>
<p>Sorry, this account has already been activated.</p>
<% } else { %>
<p>Your account has been activated, you're good to go.</p>
<% } %>
Change your view output to:
<h2>Confirmation</h2>
<p><%= ViewData["Message"] %></p>
Only use <%: %> syntax when you want output to be automatically HTML encoded.

Categories

Resources