ASP.NET
ASP.NET MVC 5: Conditional rendering based on the fragment (anchor) tag !
Gravatar is a globally recognized avatar based on your email address. ASP.NET MVC 5: Conditional rendering based on the fragment (anchor) tag !
  M G
  All
  Jun 7, 2017 @ 12:16am

Hi, Rich.

I'd like to add a conditional rendering to my MVC Login page based on the anchor tag. Let's say the user clicks on the Lost Password link available on the Login page (URL: /Account/Login/lost-password), I want to display the view (form) for the "Lost password" option without refreshing the whole page (some kind of client-side javascript event). Is there a way to implement this (javascript library. e.g. React.js) using razor syntax like:

@if (window.location.hash == "#lost-password") {  
   // display lost password form
} else if (window.location.hash == "#register") {  
   // display register form
} else {
   // display default login form
}

An example can be seen at login.teamviewer.com.

Thanks

Gravatar is a globally recognized avatar based on your email address. re: ASP.NET MVC 5: Conditional rendering based on the fragment (anchor) tag !
  Rick Strahl
  M G
  Jun 8, 2017 @ 02:47pm

You can't do this with Razor on the server, you have to use client side JavaScript.

Using jQuery you can do something like this:

$(document).ready(function() {
   if (window.location.hash == "#lost-password") 
     showPasswordRecovery();
   else
     hidePasswordRecovery();

   $("#btnRecoverPassword).click(showPasswordRecovery);
});

function showPasswordRecovery() {
   $("#lost-password-form").show();
   $("#login-form").hide();   
}
function hidePasswordRecovery() {
   $("#lost-password-form").hide();
   $("#login-form").show();   
}

If you're using something like Angular or React the hide/show logic can be abstracted a little more elegantly, but for simple things like this jQuery or vanilla JavaScript is easy enough.

© 1996-2017