What would be a good approach to replace {mySection} type tags using Razor? - asp.net-mvc-3

I am using MVC3, C# and Razor.
I have template paragraghs, which are stored and edited in the DB, like
"The sales data can be shown as follows: {SalesTable1}"
I would wish to substitute the {SalesTable1} bit with the result of some code(most likely razor) that iterates through the "Sales" class, ie
<table>
#foreach var item in Sales
{
<tr>
<td>#item.Product</td>
<td>#item.Sales</td>
</tr>
}
</table>
Code above may be not quite right, but it shows the idea.
In XSLT one would call a "template" with say a name of "SalesTable1".
What would be a good approach to solving this in Razor? BTW I am using a ViewModel where I can put my template data and my real data for processing by my View.
Thanks.
EDIT: I do not need {MySection} type tags(specifically) in the template if there is a better way of doing it. However it is important that "Admins" can edit the text around these tags within the application.
EDIT2: I have a main View which calls different Partial Views depending on different topic types. Within each Partial View I am hoping to replace the {tags} with the runtime #section templates which are also specificied in the Partial View. This seems not to work. I guess because "RenderSection" commands should appear in the Layout or parent View.
EDIT3: I think I would be better off using another RenderPartial from my Partial View. However I am unsure how I would replace the {myTable} tag with #{Html.RenderPartial("myTable");}.
<text>This is a test sentence. {myTable} After table </text>
to produce:
<text>This is a test sentence. #{Html.RenderPartial("myTable");} After table </text>
Finally I do have one issue with this approach in that if the "myTable" partial does not exist, or the {myTable} is misspelled ie {MyTablee} then the application would crash. I would want it to just carry on without running the Partial View.

You can use MVC3 Sections... they are defined as follows..
#section SideBar {
// Side bar code...
}
then when you need to render them, you simply call
#RenderSection("SideBar");
There is a great post by the GU here...
http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

I have sorted this now by using replacing the tags for Partial Views.
Many thanks.

Related

Resuable content in MVC view

I have a view in which I have a DIV which opens up as a JQuery dialog. This DIV has many elements including buttons and static text (No element inside this DIV is assigned any data from any model and it's not making use of any Razor syntax). Now I want to move this DIV to
another page so as the make it reusable. So that this DIV can be used in other views. What is the best way achieve this? Should I be using MVC user control?
Please Suggest
Thanks
Put the whole DIV in a partial view in your Views/Shared-folder in MVC (or another folder if you want to) . Let's assume you call this file '_DialogView.cshtml'. You can call this partial view from your normal page as a partial view, like this:
#Html.RenderPartial('_DialogView')
keep the page in a seperate htm. then use jquery.load('mypage.htm'). you can also use hash function in load as well jquery.load('main.htm#divname')
You can also use declarative helpers. See chapter "Reusing #helpers across multiple views" in ScottGu's blog here.
MyHelpers.cshtml
#helper GiveMeInput()
{
<input type="text" name"something"/>
}
Usage
#MyHelpers.GiveMeInput()

how to apply css class on body tag using c# files

I'm using ASP.NET MVC3 with razor engine.I want to apply css class on body tag according to page call.
I want to add class name in child page and it will affect on layout page which has body tag.
and don't want to use jquery because it execute after page render.
How can i do this?
While you may have full control of the HTML a solution was what was needed so here is one ;-)
In the _layout.cshtml page
<body class="#RenderSection("BodyClass", false)">
This will look for a section in all the child pages but says don't worry if it can't find one
Then in your child views just do this
#section BodyClass {productList}
Keep it on one line and then the outputted HTML will look fine, also you can then build up the class names as well.
#section BodyClass {productList generic}
This idea goes perfect with DOM-Ready page specific code, why not checkout
http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
Or my extended version here
https://github.com/AaronLayton/H5BP-Core
My way lets you do page specific code, but allows you to keep all of the Javascript in separate pages so each page becomes easily manageable. The final step would be to concatenate and minify all the JS into 1 file ;-)
Aaron's answer above works great for MVC 3, but I found that MVC 4 chokes on the single line section statement:
#section BodyClass {productList}
Instead, you need to use:
#section BodyClass {#("productList")}
First of all jQuery's .ready function executes after the DOM is available so it's the optimal moment to start interaction with your page's elements. ( http://api.jquery.com/ready/ ) If you experience a behavior that results in styles 'flicker' you may wan't to apply display:none to body element, and removing it after you css class has been applied.
but if you really don't want to use jQuery you should consider either making a variable to hold your css class name as a part of a viewmodel your controller will be sending to Views, or going with ViewBag.CssClass that should be declared in each of your controller's actions (or in base controller's OnActionExecuting method.
Thing to consider here is understanding and following MVC pattern, where View and Business Logic should be separated. So in my opinion you should rather avoid involving controllers in view building process.
It's much easier to simply put the following in your main layout
<body class="#ViewBag.BodyClass">
Then in the content pages put:
#{
ViewBag.BodyClass = "myClass";
}
Problem solved!

How do you design a text-based view using Ember.js or some other MVC javascript framework?

I have an homemade javascript which, among other things, do some kind of text-formatting work in order to emulate a retro text-based game:
When developing it, i tried to stick close to an MVC model, and this is what i did:
The data model basically consists of a list of objects mapping strings to very specific locations in the display, like this
[{
"value":"Hello!",
"color":"blue",
"row":1,
"column":13
},
{
"value":"What is your quest ?",
"color":"red",
"row":5,
"column":10
},
/* ... some other data */]
Then my view consists of a simple <pre> tag. When my controller draws the model on the view, it iterates through each string-location pair and create a <span> for each one that is appended to the <pre> tag. To keep the formatting consistent, it also adds "blanck" span each time it is needed.
<pre>
<span> </span><span class="blue">Hello!</span><span> </span><br>
<!-- ... other lines of the scene-->
</pre>
It's pretty simple, but it worked great until i had to dynamically change a span text value, without redrawing the whole scene each time.
So i took a look on the internet and realized that Ember.js existed, it really seems to be exactly what i could use to improve my whole code.
Now, i tried to redesign it using Ember.js, but as i don't fully understand yet its features i ran into a problem:
How do you represent a 'text-based' view into an Ember.js handlebar template ?
What am i missing here?
My data model contains both the value and the position in the display, so i don't exactly see how handlebars template could fit my needs. Or perhaps dynamically generating the template is an option ?
What do you think ?
Am I choosing the wrong framework or misunderstanding its use? is it my original MVC design that is wrong ? Changing the data model for something completely different is not an option i can easily consider as it would impact everything.
Do you have any ideas on how this could be implemented using Ember or some other framework?
Any advice will be appreciated :)
I made a rudimentary example on jsfiddle on how you could use ember for this.
Each row is an object and we have an ArrayProxy holding such objects. Thus if we have 10 rows, we have 10 row objects.
The view is binding one output line per row object.
Enjoy the flying bird:
http://jsfiddle.net/algesten/YMrW3/2/
Edit: Better to {{#if}} away empty rows as pointed out by ud3323:
http://jsfiddle.net/ud3323/92b24/

Partial View or HtmlHelper for displaying list of items

I have a model that contains an IEnumerable of a list of custom objects. Each item needs to be displayed with about 6 fields and an image. So, I won't be using a grid to display the items, rather a div and styling to achieve the look I want. With that said, I'm looking for the appropriate approach. In the book I have, Pro ASP.NET MVC 3 Framework by Adam Freeman and Steven Sanderson, they give an example of doing something similar in their Sports Store application, where for each item, they use this code,
#foreach(var p in Model.Products) {
Html.RenderPartial("ProductSummary", p);
}
Most other reading that I've done, and what seems to be a preferred approach to this, would be to use an HtmlHelper that does basically the same thing.
Which is preferred and why would I use one approach over the other?
Thanks
EDIT
I should have mentions that each of my items will be enclosed in it's own form and have a submit button. This may be the reason the authors of the book I mentioned used the partial view.
In my opinion, I would go the helper route if there is a chance that the code would be reused somewhere else. Could it be used on another page? Or in another project?
Something else to think about...
Helpers also help you to encapsulate view code so that you can keep your view clean and simple. How complex is that view? Would encapsulating some of the code assist in making the code easier to read and maintain?

ASP.NET MVC 3: Get partial views inside a view folder

I want to create a FAQ page, which gets the FAQs from partial views located inside a defined view folder.
Each partial view would contain the question, the answer and some sort order field.
I can't find anything which gives me the complete list of views inside a view folder.
Update for clarification:
A FAQ would look something like this:
#model Busker.MVC.Models.FAQ.FAQModel
#{
var title = "What is xxxxx?";
}
<p>
Please register #Html.ActionLink("Register", "register", "Member") here.
</p>
The index page of the FAQ should iterate through all FAQs and first display the questions with and anchored links and then display all titles and questions in blocks.
Another approach I'm looking into, is loading the views in ViewAllFaqsModel. Havent' figured out how to get the partial view into a collection of the model though..
Your approach of using partial views is wrong. A partial view is created to be reused and not to be a file which actually contains content.
What I would do: Create a file (XML) or database which contains questions, answers and order fields, create a model for it and ouput in on your faq site.
So you could do something like this in your aspx file:
<% foreach(FAQEntry faqentry in faqentries)
{ %>
<h2><%= faqentry.Question %><2/>
<!-- And so on... -->
<% } %>
I think you only need one partial view that you render many times passing each time a ViewModel with the fields that you mentioned.

Resources