ASP.NET MVC2 Master Page PlaceHolder visibility - asp.net-mvc

asp:PlaceHolders have a visible property, and this controls whether their content is rendered on the page.
I have declared a PlaceHolder in an MVC2 Master Page and set it's visibility to false.
Please can you tell me how I can control the visibility of a PlaceHolder from within an MVC2 view template that inherits from an MVC2 master page?
This seems like a simple task, but I am struggling to see how it can be achieved. I think I should be able to get access to the PlaceHolder from within the descending view template (as with web forms code-behind) and just set it's visibility there but the way to do this is escaping me...

Don't do this. Placeholders are legacy from classic WebForms. Manipulating server side controls in an ASP.NET MVC application is very bad and you should never do it. So simply forget about setting properties on user controls. Fortunately in Razor placeholders have been completely removed and replaced by sections. So don't write code that you won't be able to migrate later.
One way to show/hide sections of your code in an ASP.NET MVC application is to use an if statement in your views. For example:
<% if (Model.ShouldShowSection) { %>
<div>Some super section</div>
<% } %>
In this example we are testing a boolean value on the view model which the controller action that rendered this view would set.

Related

sitecore mvc ControllerRenderer and the context item Layout

Just playing around with Sitecore 7 and MVC, and I try to get the rendering basics working.
So far, I have been able to create a View Rendering (and mapped to the relevant .cshtml file) within the Renderings section, and applied these to the presentation details of the item (in much the same way you do with ASPX Layouts/ASCX Sublayouts).
I have also been able to map the Item to a controller (using the Controller and Action fields on the item), have the Index action on the controller (inherited from SitecoreController) return the view ~/Views/Home/Index.
The issue I can't seem to wrap my head around is merging the two rendering methods. I want to be able to create controllers that map to an Item, but render the item using the ViewRenderer, rather than using the default MVC conventing of return View(), so that I can:
Specify the location of the view files within a multi-site environment by setting the path parameter of the rendering; and
Have content authors/managers manage the renderings the way that the Layout/Sublayout does with place holders.
Does anyone know of a way that this can be achieved?
Have you taken a look at Controller Renderings in Sitecore MVC? These give you the ability to map a controller class to a Sitecore presentation item that can be statically or dynamically bound to your layout details.
This post has a reasonable overview of how to get started with controller renderings.
As for specifying the location of View files for multi-site environments you can pass the path to the razor file into the Controller View method, for example:
return View("~/Areas/SampleArea/Views/SampleArea/Index.cshtml");
I hope this helps.

How Can I Hide Specific Elements on a Razor View Based on Security without Logic in View?

I have looked all over for elegant solutions to this not so age-old question. How can I lock down form elements within an ASP.Net MVC View, without adding if...then logic all over the place?
Ideally the BaseController, either from OnAuthorization, or OnResultExecultion, would check the rendering form elements and hide/not render them based on role and scope.
Another approach I have considered is writing some sort of custom attributes, so as to stay consistent with how how we lock down ActionResults with [Authorize]. Is this even possible without passing a list of hidden objects to the view and putting if's all over?
Other background info: We will have a database that will tell us at execution time (based on user role/scope) what elements will be hidden. We are using MVC3 with Razor Viewengine. We're utilizing a BaseController where any of the Controller methods can be overridden.
Any help on this would be deeply appreciated!
You could use a number of different methods:
Send the user to a different view (display only view) based on the action filter, or a condition in the controller.
On a field basis, you could build the logic into the editor templates to read custom data-annotations based on role/permission.
You can build HTML helpers to handle the logic and render the appropriate partial view, css class, or text.
For more reading:
How much logic is allowed in ASP.NET
MVC views?
ASP.NET MVC 2 Templates, Part 1: Introduction (there are 5 parts, very informative and a good place to start developing your own editor templates)

Custom controls with ASP.NET MVC Razor

How can I use custom controls with ASPNET.MVC Razor?
I want to use a custom control on a Razor view. for instance:
<mycontrols:something>#Model.MyVar</mycontrols:something>
or
<mycontrols:something myattribute="#Model.MyVar" />
Please note that my goal is to use only few controls derived from MvcControl, only for trivial repetive ui stuffs.
I tried to find out a syntax similar to #Register to write on the top of the view, but without any success.
Then I went to the web.config, adding
<pages>
<controls>
<add tagPrefix="mycontrols" namespace="mynamespace" assembly="myassembly"/>
</controls>
</pages>
but it looks like custom controls are ignored in rendering.
Someone could help?
...Might be it is a little bit old fashion, but sometimes also custom control could be useful to make your code cleaner!
The Razor syntax does not support the notion of Controls at all. If you want to use controls you will have to use the ASPX (WebForms) syntax.
However, the recomended MVC pattern is to use html helper functions or partial views. In Razor you can also use the #helper syntax for quick helper functions.
In ASP.NET MVC custom server controls should be avoided. Most of them rely on ViewState and PostBack which are notions that no longer exist in MVC. You should prefer using templates, HTML helpers to implement some reusable functionality. Another problem with controls is most of them encapsulate some business logic which fetches data from somewhere and renders it which is an anti-MVC pattern. In MVC it is the controller responsibility to manipulate the model and fetch data and pass a view model to the view which simply should display it.
MVC uses partial views rather than custom controls, and they can be used in two ways that cover pretty much everything a custom control can do
RenderPartial which renders data already retrieved by the page controller
RenderAction which is similar but has its own controller action so can get data independently
The only scenario I can think of where it would be worth putting a custom control on an mvc view is if you are working on a partially migrated webforms project, and I doubt that would work with anything other than the WebFormsViewEngine.
You can do this, though I don't recommend it, though I'm not here to judge. I might add that I don't expect postback and view state to continue working either but you can at least render all of the html.
The only way to do this is a bit of a hack, because razor doesn't support webforms view engine controls. However, it does support partial views made in the webforms View engine. So a hacky solution is to include a partial view with your control in it as such:
For example, say you want to use the office web ui ribbon in your mvc3 project, you could do so by including
<body>
<div>
#Html.Partial("_RibbonPartial")
</div>
</body>
in your view. Where _Ribbon is of type .aspx
then in your partial view simply use your control and set runat="server" and put it inside of a form with runat="server"
//_Ribbon.aspx
<form id="form1" runat="server">
<XyzControls:Manager ID="Manager1" runat="server" UITheme="Silver" />
<XyzControls:OfficeRibbon ID="OfficeRibbon1" runat="server" ApplicationMenuColor="#267c29"
ApplicationMenuText="Item" ApplicationMenuType="Backstage">
//... rest of control code
</form>
Then you need to use ajax to implement events instead of using postback.
Then to cleanup, get rid of the generated code from webforms view engine for post back that you don't need.. You can try keeping it, I haven't so I'm not sure what will happen. I know there are ways to have a fake viewstate as well if you really want to get into messy hacky stuff, but to remove the extra code from webforms you can use the following jquery:
$(function ()
{
// we don't need any of the webforms stuff
$("#__EVENTTARGET","#aspnetForm").parents("div:first").remove();
$("#__EVENTVALIDATION","#aspnetForm").parents("div:first").remove();
});
I had the same demand. Wanted to use custom webcontrol from Razor/MVC page. One should not do that with controls, that is handling postback. You don't have the eventcycle to support that, but if your only demand is to use a 'rendering control', you could instantiate it in razor, and control where the rendering takes place:
#{
var myControl = new mycontrols.something();
myControl.myattribute = Model.MyVar;
mycontrol.RenderControl(new HtmlTextWriter(this.Output));
}

JavaScript/jQuery insert ASP.NET MVC ViewUserControl into form

I have existing ASP.NET MVC View pages and View user controls which I currently use in normal straightforward ASP.NET MVC fashion, sometimes I use RenderPartialView or RenderAction, etc.
By themselves they include tag. I would like to dynamically load either Views or ViewUserControl based on the selection in a dropdown list.
I'm having trouble deciding should I remove from Views and controls and put it just into the one View that will do dynamic rendering or to leave it there and leave outside of the .
What do you think and how would you go about it?
I would probably try to load the contents of a div after doing an AJAX call to get the contents. See the AJAX get call in the jQuery docs.
Or are the possibilities of what control to load so small you could just hide/show div's that are already in the page?
You can use JQuery to get the HTML from your Partial views and substitute it in the div. It could be something like this:
$.get('/Controller/Action',function(data){
$('div').innerHtml(data);
});
I did it this way and it works. /Controller/Action can be a partial view which returns HTML.

Naming of ASP.NET controls inside User Controls with ASP.NET MVC

I am wondering if there is a way to make ASP.NET controls play nicely with my ASP.NET MVC app. Here is what I am doing.
I have an order page which displays info about a single Order object. The page will normally have a bunch of rows of data, each row representing an OrderItem object. Each row is an ASP.NET User Control. On the user control there is a form element with two text boxes (Quantity and Price), and an update button.
When I click the update button, I expect the form to post the data for that individual OrderItem row to a controller method and update the OrderItem record in the database.
Here is my problem: When the post happens, the framework complains because the fields on the form don't match the parameters on the controller method. Each form field is something like "OrderItem_1$Quantity" or "OrderItem_2$Price" instead of just "Quantity" or "Price" which would match my method parameters.
I have been told that I can overcome this by making sure that the IDs of all my controls are unique for the page, but allow the NAMEs to be repeated between different forms, so that if a form for an individual row is posted, the name can be something that will match what is on my controller method.
The only problem is that I am using ASP.NET controls for my text boxes (which I REALLY want to continue doing) and I can't find any way to override the name field. There is no Name propery on an ASP.NET control, and even when I try to set it using the Attributes accessor property by saying "control.Attributes["Name"] = "Price";" it just adds another name= attribute to the HTML tag which doesn't work.
Does any one know how I can make this work? I really don't like all of the HtmlHelper functions like TextBox and DropDown because I hate having my .aspx be so PHP or ASP like with the <%%> tags and everything. Thanks!
I think you're straddled between two worlds of ASP.NET WebForms and ASP.NET MVC. You really need to use the Html.TextBox methods, etc. in MVC. This gives you complete control over the markup, which is one of the main benefits of MVC.
The very problem you're having with control over the generated HTML, e.g. getting two name attributes, is exactly what MVC is designed to address. If you stop fighting it and go with the flow, it'll work much better.
<% %> tags aren't a problem unless you have logic in there. Putting simple presentation logic on your view is fine.
If you don't like this, then maybe it's better to stick with standard ASP.NET.

Resources