ASP.NET MVC 3 Razor Syntax - Casting - c#

So, simple question really. :)
I had this following code with ASPX View Engine:
<strong><%: ((City)Model.Location).Name %></strong>
Which renders
Los Angeles
If i do this with Razor View Engine:
<strong>#((City)Model.Location).Name</strong>
^
|
syntax highlighting stops here
It renders this:
(really huge object name must be .ToString).Name
So, the highlighting cuts off at Location), and it's treating the .Name code i have (which is a property on a City object) as pure HTML.
Why is it deeming the ) as the end of the Razor code block?
Any ideas?
Also - is there a Razor reference which has all the syntax/keywords? (it took me a while to figure out that <% Import Namespace is #using with Razor).
Thanks Guys!

Does <strong>#(((City)Model.Location).Name)</strong> work? I think it's thinking the expression contained within #() is closed.

Also, for slightly easier reading...
<strong>#( (Model.Location as City).Name )</strong>

Related

How display data generated by Rich Text Editor in ASP.NET MVC? [duplicate]

I have a controller which generates a string containing html markup. When it displays on views, it is displayed as a simple string containing all tags.
I tried to use an Html helper to encode/decode to display it properly, but it is not working.
string str= "seeker has applied to Job floated by you.</br>";
On my views,
#Html.Encode(str)
You are close you want to use #Html.Raw(str)
#Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces.
You should be using IHtmlString instead:
IHtmlString str = new HtmlString("seeker has applied to Job floated by you.</br>");
Whenever you have model properties or variables that need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:
#Html.Raw(str)
Compared to:
#str
Also, I also think it's a bit safer vs. using #Html.Raw(), as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).
I generally try to avoid using Html.Raw() whenever possible.
One other thing worth noting, is I'm not sure where you're assigning str, but a few things that concern me with how you may be implementing this.
First, this should be done in a controller, regardless of your solution (IHtmlString or Html.Raw). You should avoid any logic like this in your view, as it doesn't really belong there.
Additionally, you should be using your ViewModel for getting values to your view (and again, ideally using IHtmlString as the property type). Seeing something like #Html.Encode(str) is a little concerning, unless you were doing this just to simplify your example.
you can use
#Html.Raw(str)
See MSDN for more
Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which
renders unencoded HTML.
I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field.
Example: input field: "The quick brown fox" Displayed value: "The"
The resolution was to put the variable in quotes in the value statement as follows:
<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
onchange="validateInteger(this.value)" value="#ViewBag.respondingRangerUnit">
I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.
I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.
So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.
I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.

Change razor syntax

How can I change razor syntax in RazorEngine?
I need to use specific keyword instead of"#" symbol.
For example: $$Model.someField instead of #Model.someField. ("$$" instead of "#").
You can't. Razor is not really designed in a way to do it. Basically (Microsoft.AspNet.)Razor has some specially written parsers which handle "#" in a special manner (by switching parsers). This means the languages (C#, Html in this case) itself need to be compatible with this procedure as well!
If you want to replace "#" with something else you need to rewrite the Razor Parsers. This is possible, but at this point you already implemented the hardest part of Razor yourself...
The real question you should ask yourself (or answer here) is: Why you want to do it? It is not as trivial as one would think, I was at this point before.
As freedomn-m suggested you should use #Html.Raw("#") or ## if you need to output a "#".
matthid
- a RazorEngine contributor

asp.net mvc razor foreach loop adding id to div

I am trying to add dynamic id to div inside a foreach loop concatenated with value of variable i. It throws syntax errors. What might be the issue. Can we achieve this solution without using a for loop ?
#{int i=1;}
#foreach (var or in Model.Names)
{
<div oid="#or.Id" mode="0" oids="#or.Id" id="tr"+i>
#or.Name
</div>
i++;
}
You want to construct ID in C# segment of code. One option is to do whole construction with string format:
<div oid="#or.Id" mode="0" oids="#or.Id" id="#string.Format("tr{0}",i)">
Or id="#("tr"+i)" or id="tr#(i)"
Note that you can't do just id="tr#i" because the Razor syntax parser ignores "text#text" as it looks like a normal email address.
You can't append like this:
id="tr"+i>
It must be:
id="tr#i">
You need the #.. since it won't be able to deduce between markup and Razor at that point.
in the newly C# 6 you can directly use id="#($"tr{i}")"
for myself, none of this solutions worked but adding my #i first did work, id="#i+AnyText"
after building it, and inspecting ill get id="1+AnyText", for the
next one id="2+AnyText" and so on (im using 2013vs)..
hope that helps anyone, have a nice day.
After struggling with this for a while I found that id="#("tr"+i)" did the job for me

Using Razor Templates to produce a .aspx page

I am trying to use a Razor template to produce a .aspx page as output. I'm not having luck looking in the documentation for how to do this. The Page and namespace declarations are breaking the template:
<%# Page Language="C#" Title="#Page.Metadata.browser_title" %>
<%# Import Namespace="System.Xml" %>
These are causing this error:
TemplateCompileException: CS1501: No overload for method 'Write' takes 0 arguments Line 27 Column 1: Write();
I assume this is because Razor templates using C# syntax makes the two conflict, since the declarations above use "#". Is there a way to get them to work together so a Razor template can produce an output with C# in the rendered product after the template is run? The example above also shows how the value for "Title" needs to be rendered out of the template.
The #s in the <% are invalid Razor syntax.
You need to escape them by writing <%##.
If you like Razor, maybe you should check out DD4T (http://code.google.com/p/dynamic-delivery-4-tridion/). It allows you to build a web site using ASP.Net MVC with Razor views.
You could write a C# TBB to add the tags after all your Razormediator templates or even better if you could add after the Default Finish Actions(if you're using one).
Quick and dirty sample code...
Item OutputItem = package.GetByName(Package.OutputName);
string OutputText = OutputItem.GetAsString();
// Page tag declaration..
string pagePretags = #"<<TWO LINES OF DECLARATIONs..>>"
string FinalOutputText = pagePretags + OutputText ;
OutputItem.SetAsString(FinalOutputText);
Hope this helps..

In Mvc 3 razor view what is the best way to conditionally render html based on Nulls in the model

This is I am sure an easy question but I am having trouble figuring this out.
I want to do something like this....
#(string.IsNullOrEmpty(Model.CustomerUrl) ? "" : Click me)
This snippet doesn't work.
The mixing of the html with the razor syntax and the inclusion of quotes in the attributes of the tags is making it hard to figure out.
I love razor except figuring out this kind of stuff is really tripping me up.
I would love to just not render the following at all if the CustomerUrl was null or empty...
<p class="customerLink links">#Model.CustomerName</p>
EDIT
This is still not working for me...thanks for the suggestion though.
My issue is that the above code is ALREADY in a Razor Code Block. Here is my actual code that I cannot figure out...
EDIT NUMBER TWO - THE following code is now working
#if (Model.Count() > 0)
{
foreach (var partner in Model)
{
<li>
#Html.ActionLink(#partner.CustomerName, "Details", "Customer", new { id = Customer.AID }, null)<br />
#partner.Street<br />
//this is what i cannot figure out!!
#if(!string.IsNullOrEmpty(partner.Phone))
{
#partner.Phone#:<br />
}
#partner.Distance<br />
</li>
}
}
I preceded the nested block (the if) with the # symbol. Then the markup I had to delimit with #: Then it worked.
It seems yesterday when I tried to use a nested razor code block I got a compiler error BECAUSE I preceded it with an #. So now I am more confused than ever.
In fact...if I tried to surround my #partner.Phone with quotes like this... "#partner.Phone"#:</ br> I get another compiler error. Razor is great when it works but when it doesn't it is very confusing.
Seth
Don't do an inline if.
#if(!string.IsNullOrEmpty(Model.CustomerUrl))
{
Click me
}
'Nuff Said
#if (Model.Count() > 0)
{
Presumably before this line you had html display, so to denote to razor you're using code, you need the # symbol.
foreach (var partner in Model)
{
You're within a code block already, so the # symbol wouldn't work here.
<li>
By using an html tag, razor realizes you're displaying HTML again. All content within here is assumed to be HTML. If you want to tell Razor you have code within here, you need to use the # symbol to denote the code.
#if(!string.IsNullOrEmpty(partner.Phone))
{
#partner.Phone#:<br />
}
This is correct because you need to tell Razor you're using code again. Note if this if was directly ABOVE your list tag, you wouldn't use the # symbol here, because you don't use the # symbol when you're already within code.
"#partner.Phone" doesn't work for the same reason
if(something)
""
wouldn't work in C#. You're creating an object within code without using it.
Hope that helps explain it.
One of the suggestions that you will find on the Internet regarding conditional output and View is that the two should not be mixed together. If there is something that you need to display based on some condition then you should create an HTML Helper. However, in order to answer your question what you could do (if you don't want to bother with a helper) is something like this:
#if (!String.IsNullOrWhitespace(Model.CustomerUrl))
{
<p class="customerLink links">
#Model.CustomerName
</p>
}

Categories