How to render specific fields from _Layout.cshtml - c#

I have pages like Home.cshtml and _layout.cshtml. Header, Menubar and Footer classes In _layout.cshtml. I want only Header and Footer to my Home.cshtml, How to get?
Following In _layout.cshtml
<html lang="en">
<head>
</head>
<body>
<div class="header">
/*code*/
</div>
<div class="Menubar">
/*code*/
</div>
<div class="Footer">
/*code*/
</div>
</body>

Please try with the below code snippet.
_layout.cshtml
<body>
#section header
{
<div class="header">
/*code*/
</div>
}
#section Menubar
{
<div class="Menubar">
/*code*/
</div>
}
#section Footer
{
<div class="Footer">
/*code*/
</div>
}
</body>
Home.cshtml
#RenderSection("Menubar", false)
Note : I have added three section for your respective div. By default it will shows its content in all page. If you want to hide any section from any view then pass second parameter as false.

Related

Error in asp .NET core: Partial component doesn't work

InvalidOperationException: A view component named '../../Shared/Component' could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with 'NonViewComponentAttribute'.
Screenshot
#model ShopApp.WEBUI.ViewModels.ProductViewModel
#{
var popularClass = Model.Products.Count > 2 ? "popular" : "";
var products = Model.Products;
var categories = Model.Categories;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style>
body {
margin: 0;
padding: 0;
}
main {
display: inline;
}
.popular {
color: orangered;
}
</style>
</head>
<body>
#await Html.PartialAsync(#"../../shared/_navbar")
#await Html.PartialAsync(#"../../shared/_header");
<main>
<div class="container">
<div class="row">
<div class="col-md-4">
#await Component.InvokeAsync(#"../../Shared/Component",categories)
</div>
<div class="col-md-8">
#if (products.Count == 0)
{
#await Html.PartialAsync(#"../../shared/_NoProduc");
}
else
{
<div class="row">
#foreach (var product in products)
{
<div class="col-md-2">
#await Html.PartialAsync(#"../../shared/_product", product)
</div>
}
</div>
}
</div>
</div>
</div>
</main>
</body>
</html>
Change name of component folder to Components and then create folder in that with Categories name and then put Default.cshtml in it.
call like this
#await Component.InvokeAsync("Categories", new { place your parameters here })
CategoriesViewComponent must inheited from ViewComponent
your parameters must be declared in the InvokeAsynk method of CategoriesViewComponent class and use it with its name where you want to Invoke this component: new { parameter1 = "value" }

Dynamically add the rows in table

Suppose we select the row in gridview then we get the one number from gridview. Suppose we get 8 number from gridview then how to add the Eight rows in html table with textboxes. is it possible, and how it use with jquery .append(), Thanks in Advance.
I am not sure that I understand the question properly, but yes it is possble and very simple with jquery. Your script should look something like:
function appendTable(numberOfRows) {
var row = '<tr><td><input type="text" class="yourInput"></td></tr>'; //you should change this for your needs
for (var i = 0; i < numberOfRows; i++) {
$('#yourTable').append(row);
}
}
Here is a complete example for add row and remove row :
<!DOCTYPE html>
<html>
<head>
<title>Add / Remove Row</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript"
src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".btn-add").on('click', function() {
var singleRow = $(".singleRow").eq(0).clone();
singleRow.find('.btn-add')
.removeClass('btn-succcess')
.addClass('btn-danger')
.removeClass('btn-add')
.addClass('remove')
.html("X");
singleRow.find('input').each(function(i, input) {
$(input).val('');
});
$("#wrapper").append(singleRow);
});
$(document).on('click', ".remove", function() {
$(this).parent().remove();
});
});
</script>
<style type="text/css">
.singleRow {
padding: 10px 0;
}
</style>
</head>
<body>
<div class="container">
<form role="form" autocomplete="off" id="wrapper">
<div class="row singleRow">
<div class="col-md-3">
<input class="form-control" name="name[]" type="text">
</div>
<div class="col-md-3">
<input class="form-control" name="phone[]" type="text">
</div>
<div class="col-md-1">
<select name="opt[]" class="form-control">
<option>1</option>
<option>2</option>
</select>
</div>
<button type="button" class="btn btn-success btn-add">
+
</button>
</div>
</form>
</div>
</body>
</html>

Why layout does not integrated

I have a ASP.NET Web API that run on Katana and use Razorengine for generating views.
So I created a view without layout and it works as expected.
View.cshtml
<h2>View</h2>
On browser
So when I am going to add a layout like:
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>View</h2>
After the request I've got just a blank site.
What am I doing wrong?
Update
The controller code:
public class CustomersController : ApiController
{
[HttpGet]
[Route("customers")]
public IHttpActionResult View()
{
return new ViewResult(Request, #"Customers\View", null);
}
}
and _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
But when I replaced the layout with other structure:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
#RenderBody()
</body>
</html>
Then it works. The layout template is wrong.

System.Web.HttpException: Section not defined

I have the following _Layout.cshtml:
#using System.Web.Optimization
<!DOCTYPE html>
<html>
<head>
<title>Structured Content </title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
#Scripts.Render("~/bundles/jquery")
</head>
<body>
<div id="layout">
<div id="header">
<div class="menu_header">
<h2 style="float: left;">Logo</h2>
#RenderSection("menu_header");
</div>
</div>
<div id="bottom_menu">
</div>
<div id="media">
#RenderSection("media");
</div>
<div id="content">
<div id="maincontent">
#RenderBody();
</div>
</div>
<div id="footer">
Foooter
</div>
</div>
#RenderSection("scripts", required: false)
</body>
</html>
In my index.cshtml, I have the following:
#{
Layout = "../Shared/_Layout.cshtml";
}
#section menu_header {
<div class="login_menu_links">
<ul>
<li>
Top ranked▼
</li>
</ul>
</div>
<div class="sign_in_style">
<form>
<span style="display:inline-block">
<label>Email</label><br/>
<input type="text" name="email">
</span>
<span style="display:inline-block">
<label>Password</label><br/>
<input type="password" name="pass">
<input type="submit" name="submit" value="Log in">
</span>
</form>
</div>
}
#section media {
<img src="https://marshallamps.com/wp-content/themes/marshallamps/images/brand-video-overlay.jpg" width="755">
<img src="https://www.marshallheadphones.com/media/upload/pressimages/marshall/MIXEDMEDIA/EVENT/instac.jpg">
<img src="http://blog.weddingfavorsbynette.com/wp-content/uploads/2013/05/wedding-music-dj-624x416.jpg" width="498">
}
<div id="leftcontent">
<h2 class="news_title">Get discovered as a band or musician<br />here on Namn. </h2>
<ul class="info_text">
<li><img src="https://cdn3.iconfinder.com/data/icons/vote/16/medal_star_rank-512.png" width="30" height="30">Gather karma points - get ranked</li>
<li><img src="http://findicons.com/files/icons/770/token_dark/128/headphones.png" width="32" height="32">Explore new music - all genres</li>
<li><img src="https://cdn3.iconfinder.com/data/icons/gray-user-toolbar/512/social_network-512.png" width="30" height="30">Connect - with musicians and friends</li>
</ul>
</div>
<script type="text/javascript">
$('#top_ranked_menu').mouseover(function () {
$('#bottom_menu').show();
});
$('#bottom_menu').mouseout(function () {
$(this).hide();
});
</script>
When I run my application, I get the following error message:
Section not defined: "menu_header".
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Section not defined:
"menu_header".
As I can see, I have defined them?

How to execute javascript from html page

I am making a request and reading the HTML content. The problem is that 90% of the content is JavaScript. How can I make the request and not get the JavaScript?
You can see here that CurrentHtml (the contents of the response) has JavaScript that contains elements that I need:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="js/jwplayer.js"></script>
<script type="text/javascript"> jwplayer.key = "5yP+phROWS+QiNQny92l2iTFqbmzhyI/mT+Zsw==";</script>
<script type="text/javascript" src="js/kyop_mock.js"></script>
<script id="kyop-header" type="text/x-jquery-tmpl">
<img class="left" src="${verticalBar}" />
<img class="logoCabecera" src="${logo}" />
<div class= "clearAll"></div>
</script>
<script id="kyop-links" type="text/x-jquery-tmpl">
{{each(index, adContent) contentTop}}
<span class="enlacesWrapper">
{{if document != null}}
<span><a target="_blank" href="${document.fileUrl}" title="${contentTittle}" ratittle="${ratittle}" rapage="${rapage}">${contentTittle}</a></span>
{{else}}
{{if link != null && link != ""}}
<span><a onclick="showModalWindow('#kyop-modal-${index}');" title="${contentTittle}" ratittle="${link.ratittle}" rapage="${link.rapage}">${contentTittle}</a></span>
<div id="kyop-modal-${index}" class="kyop-container-ventanaModal" style="display: none;">
<div class="ventanaModal">
<div class="right">
<img src="img/cerrarGrandeAzul.png" onclick="closeModalWindow('#kyop-modal-${index}')" style="cursor: pointer; cursor: hand; padding-bottom: 6px;">
</div>
<div>
<iframe class="kyop-modal-iframe" src="${link.linkUrl}" frameBorder="0"></iframe>
</div>
</div>
<div class="fondoTransparente"></div>
</div>
{{else}}
<span><a title="${contentTittle}" ratittle="${ratittle}" rapage="${rapage}">${contentTittle}</a></span>
{{/if}}
{{/if}}
{{if contentIcon != null && contentIcon != ""}}
<img src="${contentIcon}" />
{{/if}}
<div class="clearAll"></div>
</span>
{{/each}}
</script>
</head>
<body>
<div id="cajacentral" class="kyop_cajacentral" >
<div id="cabecera" >
</div>
<div id="pie">
<div id="pie_derecha">
</div>
<div id="pie_izquierda">
<b>© BBVA S.A.</b>
</div>
<div class="clearAll"></div>
</div>
</div>
</body>
</html>
When you get a Page Source you will get everything which is on the page, that's obvious.
There are 2 things you can do!
Remove Javascript from main page and put in a .Js file and reference it on your HTML, so you will finally receive a html with just single line
Remove Javascript tag from HTML after you receive response
Something like this
node.parentNode.removeChild(node);
you can't request a page without JS from a server separately. because it's a file that the server send to clients. unless there is a web service that make it to you.
but you can parse the HTML file and clear JS tags easily.
a wonderful parser

Categories