How to check if the user is visiting the site’s root url?

The easiest JavaScript method is: var is_root = location.pathname == “https://stackoverflow.com/”; //Equals true if we’re at the root Even http://example.com/?foo=bar#hash will produce the right result, since the pathname excludes the query string and location hash. Have a look: http://anything-but-a-slash/ Root /?querystring Root /#hash Root /page Not root If you have index file(s) at your root … Read more

How do I create a MVC Razor template for DisplayFor()

OK, I found it and it’s actually very simple. In my Views\Shared\DisplayTemplates folder I have Reading.cshtml containing the following: @model System.Int32 <span id=”@ViewData.ModelMetadata.PropertyName”>@Model</span> This renders the correct tag using the name of the property as the id attribute and the value of the property as the contents: <span id=”Reading”>1234</span> In the view file this can … Read more

Auto refresh in ASP.NET MVC

You could do the same in MVC: <script type=”text/javascript”> function timedRefresh(timeoutPeriod) { setTimeout(function() { location.reload(true); }, timeoutPeriod); } </script> <body onload=”JavaScript:timedRefresh(5000);”> … </body> or using a meta tag: <head> <title></title> <meta http-equiv=”refresh” content=”5″ /> </head> <body> … </body> or in your controller action: public ActionResult Index() { Response.AddHeader(“Refresh”, “5”); return View(); }

How to display a list using ViewBag

In your view, you have to cast it back to the original type. Without the cast, it’s just an object. <td>@((ViewBag.data as ICollection<Person>).First().FirstName)</td> ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics. … Read more

signalR – getting username

When using SignalR hubs you can use the HubCallerContext.User property to: Gets the user that was part of the initial http request. So try it with: public Task Join() { string username = Context.User.Identity.Name; //find group based on username string group = getGroup(username) return Groups.Add(Context.ConnectionId, group); }

With FileStreamResult, how is the MemoryStream closed?

The FileStreamResult will do that for you. When in doubt always check the code, because the code never lies and since ASP.NET MVC is open source it’s even more easy to view the code. A quick search on Google for FileStreamResult.cs lets you verify that in the WriteFile method the stream is correctly disposed using … Read more