Hide email or website addresses unless authenticated - asp.net-mvc

I'm developing a job board website with ASP.Net MVC and want to block any email or website addresses from being visible to unregistered users.
So for example if an employer posts a job and includes something in the description like 'To apply send an email to myemail#email.com', I want it to display 'To apply send an email to hidden link - please login or register' or words to that effect. When they login the links then become available.
I'm still very much at the learner stage with ASP.Net MVC so I'm not really sure where to start with this. I'm not sure if this is the right thing to do or if there is an alternative approach.
Many thanks for any help.

only777,
you may be best served by creating an DisplayTemplate for email addresses and running your code thro those. here's an example of what i mean. Inside your view:
<%: Html.DisplayFor( m => m.Email, "ViewIfAuthenticatedTemplate" ) %>
and then under views/shared/DisplayTemplates, add an item called ViewIfAuthenticatedTemplate.ascx and add the following code to it:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% if(Request.IsAuthenticated) { %>
<%: Model %>
<% } else {%>
<%: Html.ActionLink("hidden link - please login or register", "MyAction", "MyController") %>
<% } %>
not sure if the syntax is 100% correct, but you get the gist..
[edit] - in fact, you could use this DisplayTemplate for ANY text that had to be hidden if not authenticated.

Use a regex search to look for email addresses in the posting and replace that with the link you want for the unregistered users.
[Updated]
public ActionResult ShowPosting()
{
var description = descriptionFromDB();
if(!registeredUser)
{
model.Description = logicToReplaceTheEmailAddress(description);
}
else
{
model.Description= description;
}
return View(model);
}

Related

Can't get RedirectToaction to show completely new page using Ajax.BeginForm in MVC

Hoping someone can help me solve this issue.
I'm using Ajax.BeginForm quite often when I need to update a part of my actual webpage. But if I have a second button in the web form where I need go to a complete different page, and for example do a search and get some values that I need to complete the form. The page turns up in the update panel (updateTargetID) instead of in a complete new View. That is happening even id a do a RedirectToAction in the controller. Of course the ajax.beginform does what I accept it to do, in other words update the panel that shall be updated. But is there a way to get ajax.Beginform to use redirectToaction without updating when the user is choosing to do for example a search instead of sending the form?
I'm working with asp.net MVC,
Problem;
<% using (Ajax.BeginForm(new AjaxOptions() { LoadingElementId = "loadingElement", UpdateTargetId = "SearchResult", InsertionMode = InsertionMode.Replace}))
{%>
<% Html.RenderPartial("Searchfields", Model); %>
<div>
<%:Html.ActionLink("blank", "Index")%>
</div>
<div id="loadingElement" style="display: none">
Load data...
</div>
<div id="SearchResult">
<% if (Model.SearchResult != null)
{
Html.RenderPartial("SearchResult", Model.SearchResult);
} %>
</div>
<% } %>
In the controller (post) I do this among other stuff;
if (Request.IsAjaxRequest())
{
return PartialView("SearchResult", data.SearchResult);
}
But before this I need to do:
if (data.SearchResult.Count() == 1)
{
return RedirectToAction("Edit", "Person", new { Id = data.SearchResult.First).Id});
}
but ofcourse if I do that the hole page i rendered in the corresponding updateTargetId,
I need to render a new view instead. So how can I for exampel use javascript to redirect oncomplete and have the values from the model sent to the script to for exampel do a window.location.replace?
I'm struggling with javascript, so please help me!

MVC - Multiple Strong Type object ...inside one view

After so many years using ASP.Net, I’m still trying to figure out how to achieve the same results using MVC.
I have a materpage with a control that is strongly type to something. When I navigate to a view of a different strongly type model ...and click on the button to execute something, I get "The model item passed into the dictionary is of type Site.Models.RegisterModel', but this dictionary requires a model item of type Site.Models.LogOnModel'".
For the sake of this example, we can take the Default MVC app that is provided with VS 2010, let’s imagine I want to change the “LogonUserControl.ascx” so that it either tells me the logged user (as it works currently) OR allow me to login from there, showing me the text boxes for username and password (therefore in this case from the home page).
So I take the control and strongly type it as:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Gioby.Models.LogOnModel>" %>
<%
if (Request.IsAuthenticated) {
%>
Welcome <b><%: Page.User.Identity.Name %></b>
[ <%: Html.ActionLink("Log Off", "LogOff", "Account")%> ]
<%
}
else {
%>
<% using (Html.BeginForm()) { %>
<div id="logon">
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName)%>
<%: Html.TextBoxFor(m => m.UserName)%>
<%: Html.ValidationMessageFor(m => m.UserName, "*") %>
<%: Html.LabelFor(m => m.Password)%>
<%: Html.PasswordFor(m => m.Password)%>
<%: Html.ValidationMessageFor(m => m.Password, "*") %>
<input type="submit" value="Log On" />
</div>
<div class="editor-label">
<%: Html.ActionLink("Register here", "Register", "Account")%>
<%: Html.CheckBoxFor(m => m.RememberMe, new { #class = "pad-left" })%>
<%: Html.LabelFor(m => m.RememberMe) %>
</div>
</div>
<% } %>
<%
}
%>
Then on the HomeController, I add a procedure as:
[HttpPost]
public ActionResult Index(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
// ==>> Check Login against your DB
// Now check if param returnUrl is empty
if (!String.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View(model);
}
I tested it from the home page … it works !!!
BUT when I navigate to the “Register” view (remember that the “LogonUserControl.ascx” is located inside the “MasterPage”, therefore visible from the Register view).
So when I click on the Register button, I get the error:
The model item passed into the dictionary is of type Site.Models.RegisterModel', but this dictionary requires a model item of type Site.Models.LogOnModel'.
QUESTION:
Does that mean that I will never be able to different pieces together into one view?
Let’s say I want to write an eCommerce site and on the home page I want to see “Most used Tags”, “Most bought products”, “Product of the Month”, “List of Categories” …all within the same view and each one with his own HTTP POST action.
If this is possible using MVC?
If I'm understanding the problem correctly, you have two Views that use the same MasterPage, but which are strongly typed against different ViewModels. The master page is able to include a Partial View that is also strongly typed, as long as its expected ViewModel is the same as that of the parent view. However, if you're using a view with a different ViewModel type, it doesn't know what to do.
Consider the following:
<% Html.RenderPartial("LogOn") %>
The above code implicitly includes the model data for the current view being rendered. It's exactly the same as if you had said:
<% Html.RenderPartial("LogOn", Model) %>
So this will only work if Model is a LogOnModel. Remember that the MasterPage is really a part of whatever View inherits it, so even if you're putting this in the MasterPage, it's as if you'd put the same code in every view that inherits it. So if your View's Model is not the same as the PartialView's Model, this won't work. One alternative is to use inheritance to ensure that every ViewModel will include all the information required by the Master Page. This approach is described in detail here.
But that approach means that you have to always use a factory to produce your view model, and every view model has to be somewhat aware of which master page it will use. In our product, we can use a different master page on the same view depending on what mode the user is viewing the site in, so it doesn't make sense to tie the ViewModel to that of the Master Page. We accomplish what you're describing using the RenderAction method, which allows you to render an entire controller action as if it were just a part of the larger view. Some of the advantages of this approach are discussed here.
So now you can have your MasterPage include whatever little partial views you want, but you separate the logic for building the ViewModel of each of these Views into an individual controller action that's responsible for that particular Partial View:
<% Html.RenderAction("LogOnBox") %>
The Action:
public ActionResult LogOnBox()
{
LogOnModel model = GetLogOnModel();
return PartialView("LogOnUserControl", model);
}
Now, regardless of what model your current view uses, your Master Page can include “Most used Tags”, “Most bought products”, “Product of the Month”, “List of Categories”, etc. Better still, these portions of the page can leverage output caching so they don't have to be regenerated with every page load if they don't change very often.

2 different routes on one page?

Hi I'm pretty new with MVC2 or MVC in general. If it's one thing I get caught up with it's routes. Like now I got this scenario. Im going from the regular site to Admin. My navigation is the same partialview on both I just do a check which data to render something like this.
<% if (!Request.RawUrl.Contains("Admin")){%>
<% foreach (var site in Model) { %>
<%= Html.MenuItem(site.BelongSite, "Sida", "Site", site.BelongSite) %> |
<%} %>
<%} else {%>
<%= Html.ActionLink("Konfig", "Konfigurera", "Admin") %>
<% } %>
My route looks like this
routes.MapRoute(
"Admin", // Route name
"Admin/{action}/{name}", // URL with parameters
new { controller = "Admin", action = "konfigurera", name = UrlParameter.Optional } // Parameter defaults
);
On my View called Konfigurera I got Edit sites and they use the route above and it works great. The navigation tho dont get no action assigned to it. It's just <a href='Admin/'>
The navigation is in the shared folder, and it is a strongly typed. Any Ideas? I been struggling with this for about a hour now
Thanks for any input
EDIT
this is just one of those omg I'm so stupid moments. Ofcause the the link gone be only <a href='Admin/' because it's the default link (as the default values of the route). I noticed this as I put more links to the Admin navigation and they was ok. Well hope this can help anybody in the same situation as I had.
I wonder how I should do if I come up with the solution myself?
Ofcause the the link gone be only <a href='Admin/' because it's the default link (as the default values of the route). So really no problem here Index always gone result in a "empty" link.

ASP.NET MVC How to apply role-based or authentication-based View rendering?

i want to show/hide certain parts of a View based on Authentication-status or Roles. For my controller actions I have extended ActionFilterAttribute so I can attribute certain Actions.
<RequiresRole(Role:="Admin")> _
Function Action() as ActionResult
Return View()
End Function
Is there a similar way (attributing) which I can use in the Views? (so not like this: How can I create a view that has different displays according to the role the user is in?)
You can access the user's logged-in roles from the view like this:
<% if (Page.User.IsInRole("Admin")) { %>
<td>
<%= Html.DeleteButton("delete", model.ID) %>
</td>
<% } %>
and maybe your extension method with something like:
public static string DeleteButton(this HtmlHelper html,
string linkText, int id)
{
return html.RouteLink(linkText,
new { ID = id, action = "Delete" },
new { onclick = "$.delete(this.href, deleteCompleted()); return false;" });
}
Obviously, I'm using JavaScript to perform an HTTP DELETE to my controller action, to prevent page crawlers from accidentally deleting data from getting my pages. In my case I'm extending JQuery with a delete() method to supplement the HTTP verb.
I new this existed, but took a while to find. Here's what I am using:
<asp:LoginView runat="server">
<AnonymousTemplate>
You are not logged in yet. Please log in.
</AnonymousTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Admin">
<ContentTemplate>
You are an Admin.
</ContentTemplate>
</asp:RoleGroup>
<asp:RoleGroup Roles="Customers">
<ContentTemplate>
You are a customer.
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
<LoggedInTemplate>
Simple Log in check
</LoggedInTemplate>
</asp:LoginView>
This allows you to show different content to different users based on their login state or credentials.

ASP.NET MVC – Database Driven Menu

I have a database menu structure which I would like to add to the site.master file.
I’ve looked at other questions on StackOverflow but cannot get this to work on my website.
How do I add a User Control to the Site.Master file?
Menu.ascx
<%foreach (MainMenuSort mainMenuSort in (List<MainMenuSort>)ViewData["MainMenuSortListDisplay"])
{ %>
<li><%= Html.Encode(mainMenuSort.MainMenuId.MainMenuName)%></li>
<%foreach (SubMenuSort subMenuSort in (List<SubMenuSort>)ViewData["SubMenuSortListDisplay"])
{%>
<%if (mainMenuSort.MainMenuId.Id == subMenuSort.SubMenuId.MainMenu.Id)
{ %>
<li><%= Html.Encode(subMenuSort.SubMenuId.SubMenuName)%></li>
<%} %>
<%} %>
<%}%>
You need to use the Html.RenderPartial method in your master page.
You will need to set the MainMenuSortListDisplay and SubMenuSortListDisplay view data keys in whatever action is calling the view that uses your master page.
In your master use this
<% Html.RenderPartial("~/Views/Shared/Menu.ascx");
The path needs to be the app relative path to the control's folder. Typically these go under Shared. You can make the structure how you want below the Shared folder.
To make this technique stronger, use a strongly typed partial. In the question you would perhaps make a new class (MenuModel) with two generic collections as properties and place it in the models folder of the application. Then in the model's constructor call a method that populates the lists.
public class MenuModel
{
public IEnumerable<MainMenuSort> OuterList {get; set;}
public IEnumerable<SubMEnuSort> InnerList {get; set;}
public MenuModel()
{
VoidThatFillsTheInnerAndOuterList();
}
This will mean that you can do this in your controller
public ActionResult ShowAForm()
{
ViewData["MenuPartialData"] = new MenuModel();
return View();
}
Having set this key, your master page can use the overload of RenderPartial, like this
<% Html.RenderPartial(
"~/View/Shared/Menu.ascx",
(MenuModel)ViewData["MenuPartialData"]); %>
This assumes that your partial is strongly typed to the MenuModel class. Then in the partial you can use the model which rewrites your code slightly
<% foreach (MainMenuSort mainMenuSort in Model.OuterList) { %>
<li><%= Html.Encode(mainMenuSort.MainMenuId.MainMenuName)%></li>
<% foreach (SubMenuSort subMenuSort in Model.InnerList) {%>
<%if (mainMenuSort.MainMenuId.Id == subMenuSort.SubMenuId.MainMenu.Id)
{ %>
<li><%= Html.Encode(subMenuSort.SubMenuId.SubMenuName)%></li>
<%} %>
<%} %>
<%}%>
Hope that helps
Try something like
<% Html.RenderPartial("Menu") %>
EDIT: Corrected a typo
You could also do it as a HTMLHelper and in the MasterPage just call <%= Html.Menu() %>. Then in your HTMLHelper you have the code to get the database records and loop through them. Here is a link I found to get you started. Note my comments as there is a bug in the code example provided. I'm still having issues handling subitems of menus, I guess I need a recursive function or something??
With the help of this link. I was able to display a menu in the site.master page.

Resources