I am trying to write this style of code from cassette using WebForms. Is this possible?
#{
var message = "Hello World!";
Bundles.AddInlineScript(
#<script>
if (someTest) {
alert('#message');
}
</script>);
}
I haven't managed to find an example of using methods with the Func<Object, Object> parameter in WebForms. Or is this because this only allowed by the Razor view engine?
<% Bundles.AddInlineScript("if (someTest) { ...") %>
Related
I'm currently stuyding MVC-5 ASP.NET and following this tutorial: https://www.youtube.com/watch?v=Fu9v2MIDlTA
I have successfully created my view and controller and therefore my HeLLO WORLD display. Now I'm currently in part 2 of the tutorial wherein I'm passing my data from controller to View.
Here are the codes:
Home Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult ShowHome()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View("Home");
}
}
}
View:
#{
ViewBag.Title = "Home";
}
<html>
<head>
<title>
WELCOME TO MVC 5
</title>
<body>
<div>
This is my homepage! <br/>
TIME: <%= ViewData["CurrentTime"]%>
</div>
</body>
</head>
</html>
The question is: Why is it that when I type the part:
<% %>, my ide is not reading it? I mean, the speaker in the tutorial is using I think Visual Studio 2013 Ultimate. When he types <% >%, there is intellisense.
I'm using Visual Studio 2013 Express for WEB, when I type
ViewData["CurrentTime"] = DateTime.Now.ToString();
The IDE doesn't recognize it and it prints this as a string. :(
Glenn you got confused between they way on how code blocks where annotated in aspx pages and how they are used in the Razor view engine nowadays.
You can see Razor in action right at the top of your View:
#{
ViewBag.Title = "Home";
}
And thats how you do it. The curly braces are optional, if you use a single expression, so in your case you could just write
<div>
This is my homepage! <br/>
TIME: #ViewData["CurrentTime"]
</div>
Scott Gu has written a pretty good article about the differences between the two systems: http://weblogs.asp.net/scottgu/introducing-razor
As a rule of thumb: If its an .aspx file, use <% %>. If it is a .cshtml or .vbhtml use #{ }
I have the following code in a view (Demo.aspx) within a ASP.NET MVC 2 project:
Demo.aspx:
<% if (!Model.IsValid) { %><%= Model.FirstName %> - <% } %><%= Model.LastName %> -
I am trying to convert it to razor view (Demo.cshtml) in the process of migrating the project from ASP.NET MVC2 to ASP.NET MVC3. After doing some analysis and following the URL: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/ for migration of the webforms to razor view, I drafted the following code equivalent in razor view:
Demo.cshtml:
#if (!Model.IsValidName)
{ #Html.Raw(Model.FirstName)
#Html.Raw("-")
}
#Html.Raw(Model.LastName)
#Html.Raw("-")
But by using the conversion tool : http://visualstudiogallery.msdn.microsoft.com/d2bfd1ca-9808-417c-b963-eb1ea4896790 , I got the following code:
Demo.cshtml:
#if (!Model.IsValidName)
{ #Model.FirstName
#Html.Raw("-")
} #Model.LastName
#Html.Raw("-")
Can anyone help to confirm which of the above is correct?
I would recommend the second approach:
#if (!Model.IsValidName)
{ #Model.FirstName
#Html.Raw("-")
} #Model.LastName
#Html.Raw("-")
The reason for this is for security purposes.
As an example the #Model.FirstName will prevent against an XSS attack where as #Html.Raw(Model.FirstName) is circumventing the encoding and making it possible if a user is allowed to update their own FirstName property.
In my code I am using a partial view (call it PV1)
<div id="div_1">
<% Html.Partial("PV1", Model); %>
</div>
and in that partial view I am using "Ajax.BeginForm" to redirect it to a particular action, hence it is doing so ...
using (Ajax.BeginForm("action1", "Forms", null, new AjaxOptions { UpdateTargetId = "div_1" }, new { id = "form1" }))
{
Response.write("I am here.");
}
public ActionResult action1(XYZ Model)
{
//
return PartialView("PV1", Model);
}
at the last line of action I am again calling the same partial 'PV1', hence it is doing this too ...
but when rendering the view it don't print or do the steps written with in partial view, it override them with and show nothing ...
Html.Partial actually returns the result of rendering the view, you want to do <%= Html.Partial() %> or <% Html.RenderPartial(); %>
Html.Partial() returns the Html and thusly must be output on the page via <%= %> and Html.RenderPartial() uses Response.Write to output onto the page and can be used with <% %>.
This is not what you would use Ajax.BeginForm for. That helper is used to create actual <form> tags that will later be submitted to the server using MVC's unobtrusive ajax (so you still need some kind of a trigger action - a button, javascript - anything that submits the form).
I'm am not very clear on what you're trying to achieve. If you want to load a partial view with ajax, I would suggest using something like jQuery's ajax load method.
I would like to change dynamically the page theme in a MVC 2 Application.
I found several solutions, but I want to use this method: in the Global.asax, change the current page theme:
protected void Application_PreRequestHandlerExecute(object sender, System.EventArgs e)
{
// cast the current handler to a page object
Page p = HttpContext.Current.Handler as Page;
if (p != null)
{
string strTheme = "Theme1";
if (Convert.ToString(HttpContext.Current.Session["THEME"]) != string.Empty)
strTheme = Convert.ToString(HttpContext.Current.Session["THEME"]);
p.StyleSheetTheme = strTheme;
}
}
But this code always returns null in "p"...
I've also tried a similar code using the event PreRequestHandlerExecute in a HttpModule and the PreInit event of a page, but the code
HttpContext.Current.Handler as Page
always returns null.
Can anyone help me?
Thank you in advance.
I don't use baked in themes, but I do use jQuery UI themes. The way I handle it is in my master page I have logic that gets the current theme from a common viewmodel. The master page is strongly typed to this view model. The common viewmodel properties are updated from user preferences and other sources in a common base controller that all my controllers inherit. I do this in OnActionExecuted. I check if the result is a ViewResult, then cast the result from ViewData on the ActionExecutedContext.Result property to my common view model and set the property. The master page uses the value of the property to build the url for the CSS file.
Model
public abstract class CommonViewModel
{
public string Theme { get; set; }
// ...
}
Controller
public abstract class BaseController : Controller
{
public override void OnActionExecuted( ActionExecutedContext context )
{
if (context.Result is ViewResult)
{
var model = ((ViewResult)context.Result).ViewData.Model as CommonViewModel;
if (model != null)
{
var preferences = ...get from database for current user...
model.Theme = preferences.Theme;
}
}
}
}
Master note it uses a custom HtmlHelper to generate the stylesheet link, you could
do it by hand.
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<...CommonViewModel>" >
<%: Html.Stylesheet( "themes/" + Model.Theme + ".css" ) %>
The technique you are talking about works for standard asp.net, not asp.net MVC. The reason is that (in general) asp.net MVC does not use the web control model that standard asp.net does, and as such there is nothing to interpret the theme setting.
#tvanfosson has some great advice. Just remember that with MVC, you have much more control over things.. but that also means you have to do more work to get some of the features that standard asp.net provides for free. MVC makes many things easier, but this is not one of them.
I'm ramping up on ASP.NET MVC and looking at how I output messages in the view. What's the best way to do something like this? Helpers? Controls? Or just as is?
<% if (ViewData.ContainsKey("message") && !string.IsNullOrEmpty(ViewData["message"].ToString())) { %>
<div class="notice">
<%= ViewData["message"] %>
</div>
<% } %>
I would use an html helper:
public static class HtmlExtensions
{
public static string GetMessage(this HtmlHelper htmlHelper)
{
var message = htmlHelper.ViewData["message"] as string;
if (string.IsNullOrEmpty(message))
{
return string.Empty;
}
var builder = new TagBuilder("div");
builder.AddCssClass("notice");
builder.SetInnerText(message);
return builder.ToString();
}
}
and in the view:
<%= Html.GetMessage() %>
Remark: don't forget to html encode the value of the message if you decide to use your code the way it is.
I think a condition like what you have is the simplest approach. A control feels a bit too "heavy" for this. Maybe a helper method if you find yourself repeating it a lot.