Render Dynamic String as Razor - c#

I'm trying to render a string that is stored in my database as if it were from a CSHTML file. Here is a sample string that I'd like to render:
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
Notice that "#DateTime.Now.Year"? Well, if this were stored in a database, how would I render this into a view and have that part of it actually render as 2014 (or whatever year it is that you're reading this)?

You can use RazorEngine (NuGet package "RazorEngine") for this.
Package Manager Console:
PM> install-package razorengine
In your code:
string template = GetYourTemplateFromDatabase();
string content = RazorEngine.Razor.Parse(template, null);
If you want to add this output to your actual view you would have to add it as an IHtmlString or use #Html.Raw(ViewBag.Content):
Controller code (for IHtmlString):
ViewBag.DatabaseCode = MvcHtmlString.Create(content);
View code:
<div>
#ViewBag.DatabaseCode
</div>

you need define a model in razor
this is a good example http://weblogs.asp.net/scottgu/asp-net-mvc-3-new-model-directive-support-in-razor

If I understand correctly, you're storing that whole HTML snippet in the database? You could do a simple String.Replace on the string you get from the database.
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© {{YEAR}} - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
And then in the view :
#Html.Raw(Model.Footer.Replace("{{YEAR}}", DateTime.Now.Year))

Related

Bootstrap classes are not working with HTML Controls in the view

In my MVC project I applied bootstrap classes to the html input controls but it is not working, before that I used html helper #Html.Editorfor but experiencing the same issue. My code:
HTML:
<div class="container">
<div class="row">
<form action="~/EditProfile/PersonalEdit" method="post" enctype="multipart/form-data">
<div class="col-lg-12 col-md-12 col-sm-12 form-group">
<input type="text" id="fname" name="fname" placeholder="First Name" class="form-control" />
</div>
</div>
</form>
</div>
HTML helper:
#Html.EditorFor(model=>model.FirstName,new {#class="form-control"})
How can I apply Bootstrap classes and make it responsive?
double check and make sure you are linking to bootstrap properly.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
View the source of this page and check if bootstrap.css is available on the page. Also check in chrome developer tools network tab for the path to css and js files. I should not be returning 404 error.

Ajax MVC partialView

I've run into a problem with rendering a partialView in my web application.
What I'm trying to do is using a #Ajax.ActionLink() to fill a div when a button/link is pressed with the content of another view. The issue I'm meeting is that instead of filling the div it reloads the content into a new page, rather than filling the div. All the other answers I've looked up says the same and my syntax is pretty much the same. Is there something in between I've missed or that I should've know before I started attempting this?
Here's my actionlink
<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">Hei</span>
<span class="icon-bar">På</span>
<span class="icon-bar">Deg</span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
<div>
#Ajax.ActionLink("Last inn partial view", "_LoadView", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "get", UpdateTargetId="result"})
</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/ajax");
Here's the div I want to fill in
<div class="content">
<div class="content background">
<div id="result">Her står det masse text</div>
</div>
</div>
</div>
Here's the controller
[HttpGet]
public PartialViewResult _LoadView()
{
return PartialView();
}
EDIT:
Forgot to mention that I've got a BundleConfig.cs set up and I've made sure it works as I'm rendering my css through it, though this is the first script I've tried.
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include("~/scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/scripts/bootstrap.js"));
bundles.Add(new ScriptBundle("~/bundles/ajax").Include("~/scripts/jquery.unobtrusive-ajax.js", "~/scripts/jquery.unobtrusive-ajax.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css", "~/Content/bootstrap-theme.css", "~/Content/bankstyle.css"));
}
}
EDIT: added some text to the question to make it clearer, bolded it out to make it clear. I'm very much open to alternative solutions
EDIT: Realized what I was really looking for was the modal framework in bootstrap. Thanks for the suggestions
Please run this in console:
PM> Install-Package Microsoft.jQuery.Unobtrusive.Ajax -Version 3.2.2
For install please follow next steps: https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/
Then you must use script file which is located in Scripts folder
Install the Unobtrusive js file:
Run in nuget: Install-Package Microsoft.jQuery.Unobtrusive.Ajax
Add this to your view:
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
This is not the the answer to the original question but an alternative soloution:
using html.action
<div id="contentContainer">
#Html.Action("Action", "Controller")
</div>
This will call an action and render the view that you return from the action.
Found out what I was really looking for was the modal framework in bootstrap. Fixed my issues in 5 minutes.

New to MVC can't get layout to work as desired

I am trying to implement what I think is a pretty standard "dashboard" layout. The trick is I know ASP.NET but not so familiar with MVC so this is a learning project.
I have read many an article and they have helped me progress right to the point where I am very stuck and confused.
Part of my confusion comes from an existing advanced MVC project that I am familiar with from a user perspective. This helps in that I am able to pick through the source code and match up what I am learning to what I have seen from the user perspective.
This is not the problem just an example...
For example I read here what I believe is a very good introduction to the concepts. (http://www.codeproject.com/Articles/383145/RenderBody-RenderPage-and-RenderSection-methods-in)
In the MVC project I get to pick through however I see in the _Layout
#if (IsSectionDefined("statusbar"))
{
#RenderSection("statusbar")
}
however #section statusbar is not defined in the _Layout. If I do a global search for #section I find this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section header
{
}
#section headermenu
{
}
#section statusbar
{
}
#RenderBody()
So am I correct in guessing that statusbar is defined but it is an empty shell?
If it is an empty shell how does it get populated...cause when the project is running the statusbar does indeed have information???
So again this isn't my problem it is just an example of how the information at hand is confusing me.
This IS the problem:I'm not sure when to use PartialView, RenderSection...etc
My layout renders goofy. What is goofy? The only thing I can think of is to show you a screenshot of what happens.
What I want...
Here is the code used to generate these pages. The tags etc. for bootstrap etc. are omitted for brevity.
_Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<title>#PageTitle</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
Header Stuff
</div>
</div>
<div class="row">
<div class="col-md-4">
#RenderBody()
</div>
<div class="col-md-8">
Main Content
</div>
</div>
<div class="row">
<div class="col-md-12">
Footer Stuff
</div>
</div>
</div>
</body>
</html>
Index.cshtml
#model DashboardModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="col-md-1">
<nav id="Navbar" class="navbar navbar-left" role="navigation">
<div id="organizer">
#(Html.Kendo().PanelBar()....etc....)
</div>
</nav>
</div>
<div class="col-md-3">
This is a place holder for my subnav...????
</div>
Stuff1Link cshtml
#model StuffModel
<div style="height:400px; border:dashed; border-width:thick;">
#{ Html.Kendo().MobileLayout().Name("mlay_PropStatus"); }
#(Html.Kendo().MobileView().....
</div>
Seems like layout is not put in Stuff1Link.cshtml
Can you put it like,
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
1.If your view just has some Html code just use "PartialView" :
#Html.Partial("_theLastPost")
2.If your view has controller for passing data it's better use "RenderAction":
#{ Html.RenderAction("_theLastPost"); }
and its controller
public PartialViewResult _theLastPost()
{
var a = (from c in db.Posts
orderby c.ID_Post descending
select c);
return PartialView(a);
}
3.I do not use render section . For more information about RenderSection go asp.net mvc layouts and sections with razor
I've got a post on my blog that discusses some of this you might want to check out.
The layout code you're referencing doesn't make much sense. The only purpose to declaring an empty section, really, is to fulfill a requirement that it exists, when you don't want to actually pass anything there. Since the layout is what defines whether it must be present or not, it makes no sense for it to exist there, empty. More than that, if you implement a section in your base layout, you'll get a runtime error because there's no place higher in the view chain where it's defined.
Long and short, to provide a place holder in your layout for a section you use:
#RenderSection("SectionName", [true|false])
The boolean param indicates whether views that utilize this layout must implement the section; false means it's optional, while true means it's required.
To implement a section in a view, you use:
#section SectionName
{
...
}
If you have a layout that inherits from another layout, that layout must implement all required sections in the layout it inherits from. If you want the the section to be available to views that utilize the sub-layout, you must redefine the section in the section implementation:
_Layout.cshtml
#RenderSection("Foo", true)
_SubLayout.cshtml
#{ Layout = "Views\Shared\_Layout.cshtml"; }
#section Foo
{
#RenderSection("Foo", true)
}
Finally, as to partial views vs. sections, it all comes down to whether you want to insert something into the layout or the view. For example, sections are most commonly used for inserting link tags to CSS files in the head or script tags before the closing body tag, where the view itself would not be able to touch directly. However, it's almost an apples and oranges comparison. Partials can be utilized in the layout, in the view, or even in a section. Whereas, sections can only be utilized in the layout.

Keep menu selection throw views

I'm using mvc to go to an index that returns a partial view then render it in the body of a layout, then the different parts of the view (edit, add, delete)I use ajax and angular to render different parts of it. So I've got one index with different parts (edit, delete, add) that render the corresponding components and update them throw ajax. The thing is that I only want to render the section in the layout corresponding to the partial view, I mean in the renderbody() where the partial is rendered. But I dont want the header of the layout to to postback in order to mantain the options selected.
Here is an image:
This is the layout, the usual mvc layout:
<!DOCTYPE html>
<html lang="es">
<head>
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
#Html.ActionLink("su logotipo aquí", "Index", "Home")</p>
</div>
</div>
<select>
<option>Option 1</option>
<option>Option 2</option>
</select>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - Mi aplicación ASP.NET MVC</p>
</div>
</div>
</footer>
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
My View:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>holaaaaaaaaaaaaaaaaaa</h2>
My controller:
public ActionResult Index()
{
return PartialView();
}
In short:
I need to know how to use partial views, to render it in the layout, mantaining the options selected and not doing post back to better look of the page.
If you don't find a good solution to your problem, consider implementing bootstrap tabs http://getbootstrap.com/javascript/#tabs
I've had a similar problem and without finding a solution I've switched from select box to tabs.
Basically you play with tabs and ng-includes like this:
<ul class="nav nav-tabs">
<li class="active"><a href="" data-toggle="tab">TabName1
<ng-include src="'myFirstPartialTemplate.html'">
</a></li>
<li><a href="" data-toggle="tab">TabName2
<ng-include src="'mySecondPartialTemplate.html'">
</a></li>
</ul>
If your view is a partial view, then it should not have the property 'Layout' set.
I would do the following:
Make your index page return a View:
public ActionResult Index()
{
return View();
}
Create a another action to return your partial:
public ActionResult MyPartial()
{
return PartialView();
}
In your index page, if you wish, render your partial in the body.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>holaaaaaaaaaaaaaaaaaa</h2>
#Html.Partial("MyPartial")
Not sure if this is what you need, but I hope it helps.

Compilation Error in mvc 4

i am using mvc 4 application. actually my application it should running correctly by suddenly it showing compilation error and cleared all the temp files also it not working please help me
My error is:
View Code
<div id="page-wrapper">
<div class="row">
<div class="#ViewBag.HideClass">
#ViewBag.Message
</div>
<div class="col-lg-12">
<h2 class="page-header"> User Registration </h2>
<input type="hidden" id="MenuId" value="#(int)MenuDetails.MenuCompanyMaster" />
</div>
<!-- /.col-lg-12 -->
</div>
thank in advane
In your view page try changing this:
value="#(int)MenuDetails.MenuCompanyMaster"
To this:
value="#((int)MenuDetails.MenuCompanyMaster)"
In Razor syntax, an # section followed by a ( will end the C# code at the nearest matching ). In this case, it's just the #(int). The MenuDetails.MenuCompanyMaster section ends up being random other markup. By wrapping everything in an extra () it indicates to the Razor parser that it's all one expression.
However, I'm not certain if that will fully solve the problem that you have.

Categories