MVC 4 how to add a <div> element conditionally - asp.net-mvc-4

Want to add a HTML (div) element conditionally. But code exerpt from my Create.cshtml does not work as the parser gets mixed up missing the end-div (the first closing "}" is no code anymore)
#if (setDiv)
{
<div class="#item.DivClass" id="#item.DivId">
}
// More code more HTML
if (setDiv)
{
</div>
}
Anyone an idea how to tackle this problem? Thanks in advance!
Gerard

You have to encapsulate your opening and closing divs in #Html.Raw(). Otherwise razor will not allow this syntax as it does not know that the div that you opened in one if statement is actually closed in another.
#if (setDiv)
{
#Html.Raw("<div class='#item.DivClass' id='#item.DivId'>")
}
// More code more HTML
#if (setDiv)
{
#Html.Raw("</div>")
}

Try this:
#if (setDiv)
{
<div class="#item.DivClass" id="#item.DivId">
}
// More code more HTML
#if (setDiv)
{
#:</div>
}

Related

Conditional HTML tag on Body tag

On an ASP.NET Core 2.1 view I have the following:
<div #{if (1==1) { <text>style="background-image: url('image.png')"</text> }}></div>
Note: I am using 1==1 just for testing ...
This renders fine but I need to apply this to body tag:
<body #{if (1==1) { <text>style="background-image: url('image.png')"</text> }}>
In this case I get the error:
The tag helper 'body' must not have C# in the element's attribute declaration area.
How to solve this?
What you are writing doesn't seem to result in valid HTML.
Here are a few ideas (in order of complexity) to get you started.
Traditional conditional
<body>
#if (1 == 1)
{
<div style="background-image: url('image.png')"></div>
}
else
{
<div></div>
}
</body>
Ternary Operator
<div style="#((1 == 1) ? "background-image: url('image.png')" : "")"></div>
Move logic to separate block
#{
var divStyle = "";
if (1 == 1)
{
divStyle = "background-image: url('image.png')";
}
}
<div style="#divStyle"></div>
Logic done server side and stored in model
#model MyViewModel
<div style="#Model.DivStyle"></div>
Inject service into View (Dependency Injection)
#inject StyleService _styleService
<div style="#_styleService.GetStyleIfTrue(1 == 1)"></div>

setting up rel="next" javascript ajax <a>

I have a tag (show more) that when user clicks it loads the next 10 results onto what is already there.
I looked around to make this seo friendly but all this talks about is ..
how can i make my relevant for seo next page (really showing more instead of next)
Rather than load with ajax, why not just hide everything after the first 10 and have the next tag show the next 10. See following example.
<style>
.hide{
display: none;
}
</style>
<div id='contain'>
<?php
//Not sure what you are loading but this is a dummy loop done in PHP
$i=0;
while($i<101){
//Set the class based on the result. If greater than 10 then hide this result.
$class = ($i<10 ? "result" : "result hide");
echo"<div class='$class'>
<p>MY CONTENT</p>
</div>";
$i++;
}
?>
</div>
<a href='#' id='showMore'>Show 10 More</a>
<script>
$('#showMore').click(function(e){
e.preventDefault();
var i = 0;
$('.hide').each(function(){
if(i<10){
$(this).removeClass('hide');
}
else{
return;
}
i++;
});
});
</script>
That is the only way I can think of solving the problem. I understand ajax is being used to speed up the query.

unexpected "{" after # in razor code in mvc4

I am getting below error in render partial in razor code, Unexpected "{" after "#" character. Once inside the body of a code block (#if {}, #{}, etc.) you do not need to use "#{" to switch to code.
#if (Model.Count() > 0)
{
<div id="mReserveForTodayPartial">
#{Html.Partial("UpdateReserveForToday.mobile");}
</div>
}
kindly help..!
Html.Partial() return MvcHtmlString so you have to do like this:
#Html.Partial("UpdateReserveForToday")
in Html.RenderPartial() case it writes to the output stream and that's why it's return type is void, so when using Html.RenderPartial() you have to do this:
#{
Html.RenderPartial("UpdateReserveForToday");
}
try this code:
#{ List<SelectListItem> listItems = new List<SelectListItem>();
foreach (var item in ViewData["Subcategory"] as IEnumerable<ApplicationOneStoreForEstore.Models.tblsubcategory>) {
listItems.Add(new SelectListItem {
Text = item.subcategory_name,
Value = Convert.ToString(item.subcategory_id)
});
}
}
If you have to bind DropDownList then You have to placed this code before Html.BeginForm(..)
Below code should resolve this issue.
#if (Model.Count() > 0)
{
<div id="mReserveForTodayPartial">
Html.Partial("UpdateReserveForToday.mobile");
</div>
}
As Razor view engine can parse the code if the statements are available with in "#{ }", So in your code "#{}" is present at "If" statement so its not required to specify again.

Can I bind data to data-win-options?

I use the control MicrosoftNSJS.Advertising.AdControl in the ItemTemplate of a ListView.
I would like to bind some datas to the following data-win-options properties : ApplicationId and AdUnitId
The source datas are correctly set and are visible in my item template, I can display them with an h2 + a classic data-win-bind on innerText property
Ads are displayed correctly if I put directly static IDs in html code but these IDs need to be loaded from a config file...
Is it possible ? Thanks
If it's not possible, can I modify directly the item template in the JS code before to be injected in the listview ?
Come to find out this is possible (I was trying to do something similar)
The syntax for the control properties must be prefixed with winControl.
Example (I'm setting the application id here but binding the html element's className and the ad control's adUnitId)
<div id="adItemTemplate" data-win-control="WinJS.Binding.Template">
<div data-win-bind="className:css; winControl.adUnitId: adUnitId"
data-win-control="MicrosoftNSJS.Advertising.AdControl"
data-win-options="{ applicationId: 'd25517cb-12d4-4699-8bdc-52040c712cab'}">
</div>
</div>
I finally found a way to perform this without real binding, by using the itemTemplateSelector function like this :
function itemTemplateSelector(itemPromise)
{
return itemPromise.then(function (item)
{
if (item.type == "ad")
{
var template = _$(".adTemplate").winControl.render(item, null);
// Access to the AdControl through the DOM
var adControl = template._value.childNodes[1].childNodes[1].winControl;
// Set options that are specified in the item
WinJS.UI.setOptions(adControl, { applicationId: item.AdAppId, adUnitId: item.AdUnitId });
return template;
}
else
{
return _$(".itemTemplate").winControl.render(item, null);
}
}
}
I had this problem in ratings:
<div data-win-control="WinJS.UI.Rating" data-win-options="{averageRating: 3.4, onchange: basics.changeRating}"></div>
I bind it via winControl:
<div data-win-control="WinJS.UI.Rating" data-win-bind="winControl.averageRating: myrating" data-win-options="{onchange: basics.changeRating}"></div>
It worked fine.
<div data-win-bind="this['data-list_item_index']:id WinJS.Binding.setAttribute" >

Disqus Plugin Explanation of Dynamic Tags

So I am using the Disqus Plugin v2.65. I am trying to edit the dsq-global-toolbar at the top of the Disqus comments.
The following tags are in disqus-comment-system/comments.php
<div id="disqus_thread">
<?php if (!get_option('disqus_disable_ssr')): ?>
<?php
// if (is_file(TEMPLATEPATH . '/comments.php')) {
// include(TEMPLATEPATH . '/comments.php');
// }
?>
<div id="dsq-content">
<ul id="dsq-comments">
however on my site there are mulitple tags (the disqus-global-toolbar div) that seem to be dynamically appended between the dsq-content div and the dsq-comments ul. Where is this coming from and where can I edit this? Any help would be greatly appreciated.
I think it is coming somewhere around line 3140 in disqus.js
You can use this code to wait for the document to finish loading completely then do your changes (client side):
$(document).ready(function() {
window.disqus_no_style = true;
$.getScript('http://sitename.disqus.com/embed.js', function() {
var loader = setInterval(function() {
if($('#disqus_thread').html().length) {
clearInterval(loader);
disqusReady();
}
}, 1000);
});
function disqusReady() {
//whatever you can imagine
}
});
window.diqus_no_style can be deleted as well as the $.getsript wrapper.
Is that what you are looking for?
Something like this (use livequery instead of live):
function disqusReady() {
$('#dsq-global-toolbar').livequery(function() {
//$(this) will refer to object
});
}
Not sure what plug-in you're talking about, but if it's WordPress, I've done the same thing. Modify wp-content/plug-ins/disqus-comment-system/comments.php by adding an event handler for 'afterRender' (fires when the content ready in the DOM, but still hidden), eg. around line 70:
config.callbacks.afterRender.push(myFunctionToModifyDisqusOutput);