How to hide specific element on page from _Layout.cshtml page - asp.net

I work on mvc 5 project.
On my _Layout.cshtml I have html element named id="topBar" this element displayed in each page.
But I have page named About.cshtml I don't want this page to display only element id="topBar" all other html elements in _Layout.cshtml I want them to be displayed normal in About.cshtml.
Any idea how can achieve described appearance above?

One simple way of achieving this (without javascript), is to set a value in ViewBag inside your about Action and use it in layout like this:
_Layout.cshtml
#if (ViewBag.ShowTopBar ?? false)
{
<div id="topBar">
</div>
}
Action inside your Controller:
public class MyAwesomeController : Controller
{
public ActionResult About()
{
ViewBag.ShowTopBar = true;
return View();
}
}

There are two options:
1. Add an ID to every body element
You could add an ID to the body of each of your pages that contains for example the Controller and Action name and then add a CSS rule to hide the topBar element on the about page.
First, let's create two string variables for the controller and action name. Do this in your _Layout.cshtml:
#{
string controller = ViewContext.RouteData.Values["controller"].ToString();
string action = ViewContext.RouteData.Values["action"].ToString();
}
Next, add the ID to the body:
<body id="#controller-#action">
In your css, you can now add a rule to hide the topbar in the about page (assuming the controller is called HomeController):
#Home-About #topBar {display:none;}
You could also use an extension method to get the controller and action name. For example something like this.
2. Use jQuery on the About page
You could add a Javascript on your about page and use jQuery to hide the topbar (I assume jQuery is already loaded):
<script>
$("#topBar").hide();
</script>

Easier way, just did that: style your page individually:
<style>
#showcase { display: none; }
</style>
Put this on the page that you want to hide, showcase is my section id. ;)

Related

UI5: change the style of list items after clicking on a button

I want to dynamically change the style of a sap.m.CustomListItem of my list when I click on a button.
I used addStyleClass and it works only in the onInit method but not in the press` function, the style has been added but the view doesn't change.
Controller
pressbutton: function(oEvent) {
var o = oEvent.getParameter("value");
MessageToast.show(o.toString());
var listitem = this.getView().byId("IDCustomerListItem");
if (listitem.hasStyleClass("myListItemClass")) {
this.getView().byId("IDCustomerListItem").removeStyleClass("myListItemClass");
this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClasso");
} else {
this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClass");
}
}
CSS
.myListItemClass {
width: 50% !important;
float: left;
}
.myListItemClasso {
width: 100% !important;
}
Here is a working example: https://embed.plnkr.co/LAv1qfsUjX0Anu7S/.
Why it didn't work
The reason why it worked only in onInit but not in the press handler is because the style was being applied to the template control. You probably have something like this in your view:
<List xmlns="sap.m" items="{/myCollection}">
<CustomListItem id="IDCustomerListItem"> <!-- template control -->
<!-- ... -->
</CustomListItem>
</List>
In onInit, the template control ("IDCustomerListItem") applies the custom style, and then the framework clones the template control for each collection item before rendering.
In the press handler, however, applying the style to the template control doesn't have any effects any longer since the list items have been already cloned and rendered. It won't trigger cloning again.
The sample solution I provided above applies the style to the list. When the user triggers an action (via Switch for example), the render manager adds a custom data attribute to the corresponding HTML element by which the CSS can be applied accordingly.
.myApp .sapMList.myList[data-awesomestyle] .sapMLIB {
/* my custom style */
}
See Binding in Control with "class" Attribute
If it works in the onInit but not inside your pressbutton event handler, I assume the following:
1) The handler is not assigned to the press event of your Button
2) Your list has many items and you are not correctly getting the IDs of the items.
It's confusing in your question what are the controls assigned to the IDs and it would be easier to check the root cause of that issue having the source code of your view as well.

How to add a script in a partial view in MVC4?

This is the code which I have in my partial view
#model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic
#using(Html.BeginForm())
{
<div>
<span style="width: 110px; float:left; text-align:center; font-size:2.5em;">#Model.Number1</span>
<span style="width: 110px; float:left; text-align:center; font-size:2.5em;">+</span>
<span style="width: 110px; float:left; text-align:center; font-size:2.5em;">#Model.Number2</span>
<span style="width: 110px; float:left; text-align:center; font-size:2.5em;">=</span>
<span>
#Html.EditorFor(model => model.Result)
#Html.ValidationMessageFor(model => model.Result)
</span>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Please note at the bottom of my code, I've got a #section, and I realized that it's not running if I set a breakpoint there. If I move that line in the _Layout.cshtml it works well, but that's not the idea.
How can I tell to MVC4 in a partial razor view that I want to add that library?
You can use
#Scripts.Render("~/Scripts/my-script.js") for .js files and #Styles.Render("~/Content/my-Stylesheet.css") for css files.
Nb: it works for a particular bundle also More details - 'http://www.asp.net/mvc/overview/performance/bundling-and-minification'
it works on any sub-pages in razor including partial views.
for more info google for the usage of these helpers
You can add the script directly at the end of the partial view html, without script section (because script section is not rendered in partial views)
<script language="javascript">
// Your scripts here
// ....
</script>
You can't render layout sections from a partial. Move the section definition to the parent page or layout.
Check out my answer How to render a Section in a Partial View, which allows you to define Scripts and Styles in any view/partial view. It also takes care of duplicate includes.
My personal take is that sections aren't a good solution for styles and javascript includes.
There is no common solution for this issue but you can do the following simplest ways:
1) You can create a set of extension method as the following:
https://stackoverflow.com/a/6671766/5208058
2) Simply move your javascript codes into a separated partial view and on your main view, render 2 partial views. One for the main partial view and the other for your scripts as the following:
{
// markup and razor code for Main View here
#Html.Partial("Main_PartialView")
}
#section Scripts
{
#Html.Partial("JavaScript_PartialView")
}
Hope it helps.
This worked for me allowing me to colocate JavaScript and HTML for partial view in same file for ease of readability
In View which uses Partial View called "_MyPartialView.cshtml"
<div>
#Html.Partial("_MyPartialView",< model for partial view>,
new ViewDataDictionary { { "Region", "HTMLSection" } } })
</div>
#section scripts{
#Html.Partial("_MyPartialView",<model for partial view>,
new ViewDataDictionary { { "Region", "ScriptSection" } })
}
In Partial View file
#model SomeType
#{
var region = ViewData["Region"] as string;
}
#if (region == "HTMLSection")
{
}
#if (region == "ScriptSection")
{
<script type="text/javascript">
</script">
}
This Stackoverflow page provided a full solution to this question: Using sections in Editor/Display templates
TL;DR: Just add the Forloop.HtmlHelpers nuget package https://www.nuget.org/packages/Forloop.HtmlHelpers/ to your project to allow you to run Javascript from Razor Partial Views and Templates in ASP.NET MVC. I have personally used this with my MVC 5 project.
If you want to include specific scripts only in some partial views and avoid spreading them unnecessarily throughout your application, you can do something like this:
Define a bundle pointing to an empty javascript file in your BundleConfig.cs:
bundles.Add(new ScriptBundle("~/bundles/empty").Include(
"~/Scripts/empty.js"
));
In the head section of your _Layout.cshtml, add this variable:
#{
ViewBag.AdditionalBundle = String.IsNullOrEmpty(ViewBag.AdditionalBundle) ? "~/bundles/empty" : ViewBag.AdditionalBundle;
}
In the bottom of your _Layout.cshtml, render any additional bundles you want:
#Scripts.Render("~/bundles/lib")
#Scripts.Render(#ViewBag.AdditionalBundle);
#RenderSection("scripts", required: false)
And finally, in the partial view in which you need any specific scripts, just add the corresponding bundle to the variable:
ViewBag.AdditionalBundle = "~/bundles/mySpecificBundle";
Partial views are rendered before the _Layout.cshtml, so you need that verification at the top of the file. It goes like this: if any partial view assigned a value to ViewBag.AdditionalBundle, then use it. Otherwise, render an empty script.
Noob trick: Define a function in an already loaded file, and call the function on partial view load.
1.Have a separate js file that you load with your usual bundle:
BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/CustomScripts").Include(
"~/Scripts/Custom/partial-view.js"
));
Load the custom script bundle like any other bundle in your layout
_Layout.cshtml
#Scripts.Render("~/bundles/CustomScripts");
define a function, in our case OnPartialViewLoad function in the custom js file:
partial-view.js
function OnPartialViewLoad() {
// ... your onLoad work
}
add a document.ready() function to the end of your partial view and call the onLoaded function.
partialView.cshtml
<script type="text/javascript">
$(document).ready(function(){
OnPartialViewLoad();
});
</script>

MVC3 - Display partialview on same page

I have a left side navigation menu on my page.. using url.action like below.. I am trying to bring in a view immediately adjacent(right side of the menu) based on what link is clicked.. I put in a div next to the navigation menu.. but have no idea how to display the appropriate contents in that div...
<table>
<tr><td><a href='#Url.Action("ActionName1", "ControllerName")'>
<img src='#Url.Content("~/Content/themes/base/images/image1.png")'/></a></td></tr>
<tr><td><a href='#Url.Action("ActionName2", "ControllerName")'>
<img src='#Url.Content("~/Content/themes/base/images/image2.png")'/></a></td></tr>
</table>
<div id="DISPLAYVIEWHERE">DISPLAY VIEW HERE based on link that is clicked</div>
In controller, ActionName1 code I have this...
public ActionResult ActionName1()
{
var model = new ViewModel();
return PartialView("PartialView1", model);
}
When I run this, the partialview1 is opened in a new page. How can I get this partial view opened in the same page as the navigation menu, immediately to the right of the menu..so based on what link is clicked, partialview1 or partialview2 is displayed next to the navigation menu... thanks for your help.
you have to use ajax in that case. you can add some class to your anchor tags like
<a class='handle' href='#Url.Action("ActionName1", "ControllerName")'>
<img src='#Url.Content("~/Content/themes/base/images/image1.png")'/></a>
<a class='handle' href='#Url.Action("ActionName2", "ControllerName")'>
<img src='#Url.Content("~/Content/themes/base/images/image2.png")'/></a>
and then you can hook up the click event of these links using jquery and send an ajax call like
$('.handle').live('click', function(){
$.ajax({
url:this.href,
type='post',
success:function(data)
{
//data contains the result returned by server you can put it in div here
$('#DISPLAYVIEWHERE').html(data);
}
});
//here you have to return false to prevent anchor from taking you to other page
return false;
});

Apply Css for elements even after postback-jquery

I have many hrefs(with dynamic Ids) in my asp.net app that have the same CssClass=MyClass.
I want these button to be hidden with a condition.
I used the .ready
$(document).ready(function() {
if(condition)
$('.MyClass').css("display","none");
});
the problem is docuement.ready doesn't execut when there is a poctback.
Postback==>Button visible.normal as i've put the code in .ready.
Is there a way to persist the code:$('.MyClass').css("display","none");
I tried to apply .live() on button load,but it doesn't work.
Any ideas?
Thanks in advance.
You can take a different approach, define the style in CSS, like this:
body.conditionClass .MyClass { display: none; }
Then apply that class to <body> on document.ready, like this:
$(function() {
if(condition)
$('body').addClass('conditionClass');
});
Now new elements with .MyClass, anywhere in the <body> will get the display: none styling.
Use the jQuery livequery plugin: http://brandonaaron.net/code/livequery/docs
live() only binds events. When you have installed the plugin, use:
$('.MyClass')
.livequery(function() {
$(this).css("display","none");
});
This will hide items of class MyClass whenever they are found, even if they are created from a Ajax response. You can even use this code in place of the ready function you are currently using.
In this case, Nick Craver's solution is better, but only if you have to evaluate condition just on page load.

Changing the generated ASP.Net <form> id?

In my ASP.Net page I have
<form id="MasterPageForm" runat="server">
However, whenever the markup is generated, it turns into
<form name="aspnetForm" method="post" action="SomePage.aspx..." id="aspnetForm">
Is it possible to set what the generated HTML id for the form is?
Note: you are seeing "aspnetForm" because you are using a master page.
I found your solution in this thread...
http://forums.asp.net/p/883974/929349.aspx
In short, this is what the answer is from that link:
Here's the responsible code for that error:
public override string UniqueID
{
get
{
if (this.NamingContainer == this.Page)
{
return base.UniqueID;
}
return "aspnetForm";
}
}
As you can see, when the naming container is different from the current page (something that happens when you use a master page) the UniqueID property return "aspnetForm". this property is rendered into the name attribute that is sent to the client in the form tag. so, if you really need to, you can create your own form by inheriting from htmlform and then override the UniqueID property or the Name property (this may be a better option).
An example custom HtmlForm class could be like this:
public class Form : System.Web.UI.HtmlControls.HtmlForm
{
public Form() : base() { }
public override string UniqueID
{
get {
if (this.NamingContainer == this.Page)
{ return base.UniqueID; }
return "f";
}
}
}
Note: You can certainly change the name of the form from "f" to something else, or have it read a dynamic value, say from a web.config file or so.
and used like so
<%#Register tagprefix="LA" Namespace="Mynamespace"%>
...
<LA:form runat="server" id="frm">
...
</LA:form>
Set the "clientidmode" attribute to "static" on the form tag to prevent the framework from overriding it with "aspnetForm". This was driving me nuts for hours.
I am agree with #Sumo's comment under accepted answer and I had the same situation.
In ASP.NET 4.0, master page, if a is not given an id, the rendered html will be automatically assigned one, such as .
Otherwise, the rendered html will have its original defined id.
change in web config
<pages controlRenderingCompatibilityVersion="4.5" clientIDMode="AutoID"/>
to
<pages controlRenderingCompatibilityVersion="4.5"/>

Resources