Show/Hide html items in mvc application - model-view-controller

i am using membership provider to get roles for the user that logged in to my application.
But, i wonder how i am hiding/showing html items on the screen based on that roles?
** I am using viewModel for each of my views in the application.
Thanks..

If your app is in ASP.NET MVC, Use this:
<% if(Roles.IsUserInRole("myRole")) { %>
<!-- show my html -->
<% } else { %>
<!-- show something else -->
<% } %>

Related

How can I render a view that is a part of my user controller on a static page like my home page?

I'm looking to place the signup form for an app I'm building on the app's home page, however I don't know how to render the view app/views/users/new.html.erb on my home page. Is there a method I can use to accomplish this? Thanks a bunch!
You can use a content_for block and then yield it on your application layout. Create a partial with your users/new page. (users/_new).
In your homepage.html.erb file add
<% content_for :homepage do %>
<%= render users/new %>
<% end %>
Then in your application.html.erb file add
<%= yield :homepage %>

Why can't I use the ASP.NET MVC 3 Razor engine (with the new #-syntax) in a UserControl?

I am creating a UserControl that will read data from an XML file and populate a ListBox. I've open up the .ascx file and would like to use #foreach (etc..) but this isn't valid?
Can someone explain why this isn't possible? Or maybe confirm if UserControls are deprecated in MVC 3?
.ascx is WebForms. # is Razor, meaning that if you want to write #foreach(...) you need a Razor template: Foo.cshtml:
#model IEnumerable<AppName.Models.Foo>
#foreach (var item in Model)
{
...
}
And if you want WebForms user control Foo.ascx:
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<AppName.Models.Foo>>"
%>
<% foreach(var item in Model) { %>
...
<% } %>

dotnetopenauth and ajax forms

I'm trying implement an openId login with Google account together with ASP.NET MVC 2 framework and DotNetOpenAuth library.
The following code is used to render login button:
<% using (Html.BeginForm("LogOnPostAssertion", "Authentication", FormMethod.Post, new { target = "_top" }))
{ %>
<%= Html.AntiForgeryToken() %>
<%= Html.Hidden("ReturnUrl", "/", new { id = "ReturnUrl" }) %>
<%= Html.Hidden("openid_openidAuthData") %>
<%= Html.OpenIdSelector(this.Page, new SelectorButton[] {
new SelectorProviderButton("https://www.google.com/accounts/o8/id", AppHelper.ImageUrl("login/google.gif")),
new SelectorOpenIdButton(Url.Content("~/Content/google.gif"))
}) %>
<% } %>
</div>
</div>
<% var options = new OpenIdSelector();
options.DownloadYahooUILibrary = false;
%>
<%= Html.OpenIdSelectorScripts(this.Page, options, null) %>
This code works fine until I want to use AJAX. I don't want to reload the whole page after user was logged in. If I change Html.BeginForm with Ajax.BeginForm the authentication stops working. "LogOnPostAssertion" action is not called.
On my site the login form is opened in popup modal dialog. I want to verify user, close the dialog and refresh user status area using javascript. As example the process should be similar to the one as at http://shopping.com
Could it be because when you switched it to AJAX that you didn't preserve the POST HTTP method?
When I tried replacing the Html.BeginForm line with this one, it worked:
<% using (Ajax.BeginForm("LogOnPostAssertion", "Auth", new AjaxOptions { HttpMethod = "POST" })) { %>
By setting a breakpoint on the LogOnPostAssertion action, I saw that it did work. But the action itself would need to be adjusted to not send redirects but rather send whatever update script is appropriate.

MVC Transfer Data Between Views

I just started to learn MVC and am trying to understand how it works.
I don't want to send users to different views for all edit, insert and list operations.
In my sample application a View contains a list of items and below the list there is a form (for inserting new items) with action "{Controller}/Create" but there is no Create View.
When a user inserts a new item it posts to the Create action with httpverb post and creates the item and returns back to the List action with RedirectToAction method.
But I can not show any message(error, information etc) to the user in this style because I can not pass data between Create action and List action. How can I do that?
You need to use Post Redirect Get PRG pattern.
Please read this Use PRG Pattern for Data Modification section in this blog post by Kazi Manzur Rashid.
http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx
This approach uses TempData to maintain ModelState data between redirects.
[HttpPost, ValidateAntiForgeryToken, ExportModelStateToTempData]
public ActionResult Create(FormCollection form)
{
Product p = new Product();
if (TryUpdateModel<IProductModel>(p))
{
productRepository.CreateProduct( p );
}
else
{
// add additional validation messages as needed
ModelState.AddModelError("_generic", "Error Msg");
}
return RedirectToAction("Index");
}
And here is your Index action method.
[ImportModelStateFromTempData]
public ActionResult Index()
{
IList<Product> products = productRepository.GetAll();
return View("Index", products);
}
And here is your Index view.
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<Product>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Products</h2>
<% foreach (var p in Model) { %>
<div><%= Html.Encode( p.ProductName ) %></div>
<% } %>
<%= Html.ValidationSummary("Please correct the errors", new { id = "valSumCreateForm" }) %>
<% using (Html.BeginForm("Create", "Product")) { %>
Product Name: <%= Html.TextBox("ProductName") %>
<%= Html.AntiForgeryToken() %>
<% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %>
<% } %>
</asp:Content>
The ImportModelStateFromTempData
and ExportModelStateToTempData
attributes helps transfer model
state errors between redirects. This
<% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %> associates the MVC Form with its corresponding Validation Summary.
You can check another answer by me on this here as well.
ViewModel with SelectList binding in ASP.NET MVC2
Let me know if you have any question.
-Soe
Most MVC frameworks have the ability to temporarily store a small bit of data just through the next request, for just this purpose. In ASP.NET MVC its called TempData, in Rails it's called :flash, etc.
This article explains how to use TempData:
One of the more annoying things to
deal with in Web programming is errors
on a form. More specifically, you want
to display error messages, but you
want to keep the previously entered
data. We've all had the experience of
making a mistake on a form that has 35
fields, only to be presented with a
bunch of error messages and a new,
blank form. The MVC Framework offers TempData as a place to store the previously entered information so that the form can be repopulated. This is
something that ViewState actually made
very easy in Web Forms, since saving
the contents of controls was pretty
much automatic. ... TempData is a dictionary,
much like the untyped ViewData.
However, the contents of TempData only
live for a single request and then
they're deleted.

MVC Multiple ViewPage items in aspx required

I need to pass in 2 objects to a page to access Model.NewsItems and Model.Links
(the first is a class of news item objects with heading, content etc and the Links are a set of strings for hyperlink depending on whether the system is up or down.
This is the page declaration
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Tolling.Models.NewsItems>" %>
If I refer to Model.Items - I am fine.
However, if I refer to Model.HyperLink1, I am not.
How can you pass in multiple objects into the page?
I have tried importing both namespaces without success - i.e.
<%# Import Namespace="Tolling.Models.News" %>
<%# Import Namespace="Tolling.Models.HyperLinks" %>
Create a ViewModel class that contains both of your model collections and then pass that too the view:
Sample Controller:
var myNewModel = new MyNewModel()
{
NewsItems = new List<NewItem>(),
HyperLinks = new List<HyperLink>()
}
return View(myNewModel);
View page declaration:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyNewModel>" %>
Then you can access them in your view with your new ViewModels properties:
<%= Model.NewsItems %>
<%= Model.Hyperlinks %>
You can pass extra data into the View by using ViewData, TempData, Session or Cache. I'd suggest you use ViewData. As described by MSDN:
Gets or sets a dictionary that
contains data to pass between the
controller and the view.

Resources