Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Meta tag in View page using MVC-5

I have two meta tag in _Layout.cshtml master page and now i want to add meta tags in someone.cshtml view page.

and i also try with this code

put in _layout.cshtml master page @RenderSection("metatags",false);

put in someone.cshtml like @section metatags { <meta ... /> }

but not get success.

and also try with add meta tag jquery but not worked fine.

like image 720
Jatin Gadhiya Avatar asked Apr 21 '14 11:04

Jatin Gadhiya


3 Answers

It should work.

Here's my master page _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    @RenderSection("metatags", false)
    <title>My ASP.NET Application</title>
</head>
<body>
    @RenderBody()
</body>
</html>

Here's the index.cshtml file

@section metatags
{
    <meta name="test" content="test"/>
    <meta name="test2" content="test"/>
}

<div>Page content</div>

The result

<html>
<head>
    <meta charset="utf-8">

    <meta name="test" content="test">
    <meta name="test2" content="test">

    <title>My ASP.NET Application</title>
</head>
<body>        

<div>Page content</div>    

</body>
</html>
like image 54
meziantou Avatar answered Oct 12 '22 23:10

meziantou


I found a way that works for now.

This solution mostly use when multiple master page.

In the controllers / action assign whatever meta info you need for that view.

ViewBag.Title = "some title";
ViewBag.MetaDescription = "some description";

In the View or master page get whatever meta info you need for that view.

 @if(ViewBag.MetaDescription != null)
    {
        <meta name="description" content="@ViewBag.MetaDescription" />
    }

    @if(ViewBag.MetaKeywords != null)
    {
        <meta name="keywords" content="@ViewBag.MetaKeywords" />
    }
like image 40
Jatin Gadhiya Avatar answered Oct 12 '22 22:10

Jatin Gadhiya


If are using nested layouts you'll need to follow this guideline:

@RenderSection in nested razor templates

The technique you're using should work, if it is not, maybe that's the reason.

But looking at the intended use in your own answer, if you only need to modify the keywords and description tags there are apis in NopCommrece for that.

In your master layout:

<meta name="description" content="@(Html.NopMetaDescription())" />
<meta name="keywords" content="@(Html.NopMetaKeywords())" />

and in the client cshtml files

@{
    Html.AddMetaDescriptionParts(Model.MetaDescription);
    Html.AddMetaKeywordParts(Model.MetaKeywords);
}

There are plenty of samples for this in the NopCommerce code.

like image 32
Marco Regueira Avatar answered Oct 12 '22 23:10

Marco Regueira