EzDevInfo.com

razor interview questions

Top razor frequently asked interview questions

Replace line break characters with
in ASP.NET MVC Razor view

I have a textarea control that accepts input. I am trying to later render that text to a view by simply using:

@Model.CommentText

This is properly encoding any values. However, I want to replace the line break characters with <br /> and I can't find a way to make sure that the new br tags don't get encoded. I have tried using HtmlString but haven't had any luck yet.


Source: (StackOverflow)

What is the @Html.DisplayFor syntax for?

I understand that in Razor, @Html does a bunch of neat things, like generate HTML for links, inputs, etc.

But I don't get the DisplayFor function...

Why would I write:

@Html.DisplayFor(model => model.Title)

when I could just write:

@Model.Title

Source: (StackOverflow)

Advertisements

Razor view engine, how to enter preprocessor(#if debug)

I am writing my first razor page today, can't figure out how to enter #if debug #else #endif

How can i enter preprocessor in razor?


Source: (StackOverflow)

How do I import a namespace in Razor View Page?

How to import a namespace in Razor View Page?


Source: (StackOverflow)

Escape @ character in razor view engine

I am creating a sample ASP.NET MVC 3 site using Razor as view engine. The razor syntax starts with @ character e.g. @RenderBody(). If I write @test on my cshtml page it gives me parse error

CS0103: The name 'test' does not exist in the current context

How do I escape '@' character?


Source: (StackOverflow)

ASP.NET MVC View Engine Comparison

I've been searching on SO & Google for a breakdown of the various View Engines available for ASP.NET MVC, but haven't found much more than simple high-level descriptions of what a view engine is.

I'm not necessarily looking for "best" or "fastest" but rather some real world comparisons of advantages / disadvantages of the major players (e.g. the default WebFormViewEngine, MvcContrib View Engines, etc.) for various situations. I think this would be really helpful in determining if switching from the default engine would be advantageous for a given project or development group.

Has anyone encountered such a comparison?


Source: (StackOverflow)

Using Razor within JavaScript

Is it possible or is there a workaround to use Razor syntax within JavaScript that is in a view (cshtml)?

I am trying to add markers to a Google map... For example, I tried this, but I'm getting a ton of compilation errors:

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.

    // Now add markers
    @foreach (var item in Model) {

        var markerlatLng = new google.maps.LatLng(@(Model.Latitude), @(Model.Longitude));
        var title = '@(Model.Title)';
        var description = '@(Model.Description)';
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }
</script>

Source: (StackOverflow)

How to use ternary operator in razor (specifically on HTML attributes)?

With the WebForms view engine, I'll commonly use the ternary operator for very simple conditionals, especially within HTML attributes. For example:

<a class="<%=User.Identity.IsAuthenticated ? "auth" : "anon" %>">My link here</a>

The above code will give the <a> tag a class of auth or anon depending on whether the user is authenticated.

What is the equivalent syntax with the Razor view engine? Because Razor requires HTML tags to "know" when to jump in and out of code and markup, I'm currently stuck with the following:

@if(User.Identity.IsAuthenticated)  { <a class="auth">My link here</a> }
else { <a class="anon">My link here</a> }

This is, to put it mildly, terrible.

I would love to do something like this, but am struggling to understand how in Razor:

<a class="@=User.Identity.IsAuthenticated ? "auth" : "anon";">My link here</a>

--

Update:

In the meantime, I've created this HtmlHelper:

public static MvcHtmlString Conditional(this HtmlHelper html, Boolean condition, String ifTrue, String ifFalse)
{
  return MvcHtmlString.Create(condition ? ifTrue : ifFalse);
}

which can be called like this from Razor:

<a class="@Html.Conditional(User.Identity.IsAuthenticated, "auth", "anon")">My link here</a>

Still, I am hoping there's a way to use the ternary operator without falling back to wrapping it in an extension method.


Source: (StackOverflow)

Styles.Render in MVC4

In a .NET MVC4 project how does @Styles.Render works?

I mean, in @Styles.Render("~/Content/css") which file is it calling?

I dont have a file or a folder called "css" inside my Content folder.


Source: (StackOverflow)

ASP.NET MVC 3 - Partial vs Display Template vs Editor Template

So, the title should speak for itself.

To create re-usable components in ASP.NET MVC, we have 3 options (could be others i haven't mentioned):

Partial View:

@Html.Partial(Model.Foo, "SomePartial")

Custom Editor Template:

@Html.EditorFor(model => model.Foo)

Custom Display Template:

@Html.DisplayFor(model => model.Foo)

In terms of the actual View/HTML, all three implementations are identical:

@model WebApplications.Models.FooObject

<!-- Bunch of HTML -->

So, my question is - when/how do you decide which one of the three to use?

What i'm really looking for is a list of questions to ask yourself before creating one, for which the answers can be used to decide on which template to use.

Here's the 2 things i have found better with EditorFor/DisplayFor:

  1. They respect model hierarchies when rendering HTML helpers (e.g if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName").

  2. More robust, e.g if you had a List<T> of something in your ViewModel, you could use @Html.DisplayFor(model => model.CollectionOfFoo), and MVC is smart enough to see it's a collection and render out the single display for each item (as opposed to a Partial, which would require an explicit for loop).

I've also heard DisplayFor renders a "read-only" template, but i don't understand that - couldn't i throw a form on there?

Can someone tell me some other reasons? Is there a list/article somewhere comparing the three?


Source: (StackOverflow)

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

I would like to have 2 separate Layouts in my application. Let say one is for the Public section of the website and the other is for the Member side.

For simplicity lets say all the logic for each of theses sites is wrapped neatly into 2 distinct controllers.

  • PublicController
  • StaffController

And that they each have a corresponding Layout for all the View under each.

  • _PublicLayout.cshtml
  • _StaffLayout.cshtml

How do I use the _ViewStart.cshtml file to specify that all View's / Action under "Public" use the PublicLayout and everything under "Staff" use the StaffLayout?

Thanks!


Source: (StackOverflow)

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

I'm trying to figure out the proper Razor syntax to get a JavaScript file for a particular *.cshtml to be in the head tag along with all the other include files that are defined in _Layout.cshtml.


Source: (StackOverflow)

ASP.NET MVC Razor render without encoding

Razor encodes string by default. Is there any special syntax for rendering without encoding?


Source: (StackOverflow)

How to get current page URL in MVC 3

I am using the Facebook comments plugin on a blog I am building. It has some FBXML tags that are interpreted by the facebook javascript that is referenced on the page.

This all works fine, but I have to pass in the current, fully-qualified URL to the plugin.

<div style="width: 900px; margin: auto;">
    <div id="fb-root"></div>
    <fb:comments rel='nofollow' href="URL HERE" num_posts="10" width="900"></fb:comments>
</div>

What is the best way to get the URL of the current page? The request URL.

Solution

Here is the final code of my solution:

<fb:comments rel='nofollow' href="@Request.Url.AbsoluteUri" num_posts="15" width="900"></fb:comments>

Source: (StackOverflow)

Serving favicon.ico in ASP.NET MVC

What is the final/best recommendation for how to serve favicon.ico in ASP.NET MVC?

I am currently doing the following :

  • Adding an entry to the very beginning of my RegisterRoutes method :

    routes.IgnoreRoute("favicon.ico");
    
  • Placing favicon.ico in the root of my application (which is also going to be the root of my domain).

I have two questions :

  • Is there no way to put favicon.ico somewhere other than the root of my application. Its pretty icky being right there at the same level as Content and Controllers.
  • Is this IgnoreRoute("favicon.ico") statement sufficient - or should I also do the following as discussed in a blog post from Phil Haack. I'm not aware of ever having seen a request to favicon.ico in any directory other than the root - which would make this unnecessary (but its nice to know how to do it).

    routes.IgnoreRoute("{*favicon}", new {favicon=@"(.*/)?favicon.ico(/.*)?"});
    

Source: (StackOverflow)