Can you use a #Helper inside an #Helper? - asp.net-mvc-3

I am not sure this is possible.
I have a bunch of #Helper's inside a view AND in other views:
#helper ViewHelper1()
{
...
}
#helper ViewHelper2()
{
...
}
etc.
I have repetitive code that is used in the view AND in other views:
#if (!(Model.Entity == Model.Enum.One))
{
<td>
#ViewHelper1()
</td>
}
else
{
<td>
#ViewHelper1()
</td>
<td>
#ViewHelper1()
</td>
}
The actual #ViewHelper1 has more complex code, but that's not important (I think).
Well, since each view has a number of #Helper's (30+ views, 10-15 #Helper's each) and the <table> structure is the same, I was wondering how to go about creating a #Helper in App_Code that encapsulates the <td> structure and then would pass the view's #Helper.
Say:
#helper Table(...)
{
...
}
Or whether or not that's even possible and then call it in the view like:
#Table(HelperView1)
If it is I just needed help with the syntax.
As always, much appreciated.

The generated razor helpers are just functions with the return type HelperResult.
You can have delegates which returns HelperResult as parameters in your main helper and call them at the appropriate places.
A small sample to get you started:
#helper View1()
{
<h1>View1</h1>
}
#helper View2()
{
<h2>View2</h2>
}
#helper Table(Func<HelperResult> viewHelper)
{
<text>Reuslt of viewHelper</text>
#viewHelper()
}
#Table(View1)
#Table(View2)
The generated output:
Reuslt of viewHelper
<h1>View1</h1>
Reuslt of viewHelper
<h2>View2</h2>

Related

Print a value which is later known in the view in Razor

Is there in Razor a way to print some HTML on the page
while the value later known in the view?
For example: I would like to print the sum of an expensive calculation, and that sum should be before the items in the HTML. But with the example below, it will always print 0.
I would like to calculate the sum only once.
I would like to solve this in the view, not in a csharp helper or on the client side (css, javascript etc)
#{
var sum = 0;
}
<table>
#* I would like to print here the sum which is known after the foreach loop*#
<tr><td>total: #sum</td></tr>
#foreach (var item in items)
{
<tr>
#{
var x= item.expensiveCalculation();
sum+= x;
}
//print item with x
<td>#x</td>
</tr>
}
</table>
edit: It is very important that the expensiveCalculation() is only calculated once for each item!
Your model is not adapted to the requirements of the view. Full stop.
So when your model is not adapted to the requirements of your view you go ahead and define a view model so that all the expensive operations are done inside the controller.
So:
public class ItemViewModel
{
public decimal Price { get; set; }
public string Name { get; set; }
}
Now your view becomes strongly typed to the view model and there are no longer expensive operations there:
#model IEnumerable<ItemViewModel>
<table>
<tr>
<td>
total: #Model.Sum(item => item.Price)
</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Name - #item.Price<td>
</tr>
}
</table>
and now inside your controller action prepare this view model and pass it to the view:
public class SomeAction()
{
IEnumerable<Item> items = ... go and fetch your domain models from wherever you are fetching them
// now let's build the view model
var model = new MyViewModel
{
Items = items.Select(x => new ItemViewModel
{
Name = x.Name,
Price = x.expensiveCalculation()
})
};
// and we are obviously passing the view model to the view, not the domain model
return View(model);
}
As you can see we are doing the expensive operations for each element inside the controller in order to bind it to the corresponding property of the view model (Price) but we are no longer paying this expensive operations price inside the view as we are simply summing over the view model pre-calculated properties.
And next time when you encounter a problem in ASP.NET MVC don't forget that view models are the solution to your problem.

Rendering Partial Views in a Loop in MVC3

I have a pretty simple scenario, Model for my view is a List.
Loop through List like
#foreach(CustomObject obj in Model)
{
Html.Partial("_TrackingCustomObject",obj)
}
So i was expecting to have number of partial views according to my list.
Partial View has been developed accordingly.
There is no error on page. It just does not show any data that is supposed to display by partial views.
What is the reason of not showing any data?
You are missing an #:
#foreach(CustomObject obj in Model)
{
#Html.Partial("_TrackingCustomObject", obj)
}
But why writing foreach loops when you can use editor/display templates? Like this:
#model IEnumerable<CustomObject>
#Html.EditorForModel()
and then simply define the corresponding editor template (~/Views/Shared/EditorTemplates/CustomObject.cshtml) that will automatically be rendered for each element of your model:
#model CustomObject
<div>
#Html.EditorFor(x => x.Foo)
</div>
Simple and conventional :-)
You're missing the Razor symbol #:
#foreach(CustomObject obj in Model)
{
#Html.Partial("_TrackingCustomObject",obj)
}
Also make sure your partial view is using the object type CustomObject as the Model.
#model MyProject.Models.CustomObject
<h1>Yeah we're in a partial! #Model.SomeProperty </h1>
To try and drill down to where the error is, try placing some static text inside the PartialView.
<p>Some text</p>
If your collection has 10 items, then you should see 10 of these paragraphs. Next once this works, focus on displaying some property in each item.
#model MyProject.Models.CustomObject
<p>Some text</p>
<p>#Model.SomeProperty</p>
When you are creating html form using #Html.BeginForm() you have to wrap the remaining stuf inside a <div> or other container else the html elements won't get rendered.
Ex.
this won't work
#using(Html.BeginForm())
{
Html.EditorFor(m => m.Name)
}
this will work
#using(Html.BeginForm())
{
<div>
#Html.EditorFor(m => m.Name)
</div>
}
Bit late in the day, but this worked for me in MVC 4:
#foreach (var p in #Model.RelatedCards)
{
Html.RenderPartial("_ThumbPartial", p);
}
Try this:
#Html.RenderPartial("_TrackingCustomObject",obj)
This is too old but someone can use it.
#foreach(CustomObject obj in Model)
{
<text>
Html.Partial("_TrackingCustomObject",obj)
</text>
}

MVC3 Razor weakly typed view?

I know this sound somewhat off-piste but how would you create a weakly typed view where you pass in a collection of objects and iterate in razor accordingly and display in a table?
-- Controller View --
???
-- Razor View ---
#foreach (var item in Model)
{
<tr>
<td>
#item.attr1
</td>
<td>
#item.attr2
</td>
</tr>
}
Frist you know the data send
From Controller -------> view by two way
By weak type view
and by strong type view
there is no other way of passing data from controller to view ...(remember)
what is intelliscence ----> which show the related sub property of any model
like we write Model. --------> then all property show in
droupdown list after dot(.).
A.what is weak type view
This is used without using model i.e like using ViewBag and other.
There is no intellisence for this type of view and it is complicated, and when you write
any name which not exist then it give at runtime error.
Ex.
.............Controller
ViewBag.List = List<job>;
return View();
.............Razor View
#foreach(var item in ViewBag.List)
{
// when you write no intellisence and you want to write your own correct one...
#item.
}
B. What strongly type view
this is used model to send data from controller to view an vice-versa.
Model are strongly typed to view so, it show intellicence and when you write wrong
then there only error show at compile time..
Ex.
.................Controller
List<job> jobdata =new List<job>();
return View(jobdata);
................view
//Mention here datatype that you want to strongly type using **#model**
#model List<job>
#foreach(var item in Model)
//this **Model** represent the model that passed from controller
// default you not change
{
#item. //then intellisence is come and no need write own ....
}
that is weak and strong type view ......
So now you solve any problem with this basic.....
may I hope it help u....
But it is best to use Strongly Typed view so it become easy
to use and best compare to weak...
#model dynamic
Will do what you want, I believe.
If its going to be a collection, then maybe use
#model ICollection
It's not weakly typed. It's typed to a collection of some kind.
#model IEnumerable<MyClass>
OK, late to the party I know, but what you're after is a view stating "#model dynamic" as already stated.
Working Example: (in mvc3 at time of posting)
NB In my case below, the view is actually being passed a System.Collections.IEnumerable
As it's weakly typed, you will not get intelesense for the items such as #item.Category etc..
#model dynamic
#using (Html.BeginForm())
{
<table class="tableRowHover">
<thead>
<tr>
<th>Row</th>
<th>Category</th>
<th>Description</th>
<th>Sales Price</th>
</tr>
</thead>
#{int counter = 1;}
#foreach (var item in Model)
{
<tbody>
<tr>
<td>
#Html.Raw(counter.ToString())
</td>
<td>
#item.Category
</td>
<td>
#item.Description
</td>
<td>
#item.Price
</td>
</tr>
#{ counter = counter +1;}
</tbody>
}
</table>
}
Edit: removed some css

MVC3 Razor and simulating same-page sections

Razor doesn't support same-page sections, so I can't do something like this:
#if (wrapSection)
{
<div class="section-wrapped-in-div">
#RenderSection("mySection")
</div>
}
else
{
#RenderSection("mySection")
}
#section mySection
{
some stuff here...
}
I know I can accomplish this with a partial view, but this is specific to this page, and really would be best kept on the same page.
Is something like this possible?
You should make a helper method:
#helper MySection(...) {
...
}
#MySection(...)
Unlike sections, helpers can also take parameters.

MVC3 Razor foreach problems

I've got a model that is returning a IEnumerable of football picks for a variable number of users. Due to this, I'm dynamically building an html table with a variable number of columns. Basically, my picks will come back like this. However, each game is going to be repeated for each User, so I'm only adding the first 3 columns of each table row once, and then adding only a single tag until the gameID changes. I know there are probably better ways to do this, but it's just a side project that I need to get done quickly. And, I just want to figure out why it's not working.
GameID
GameDateTimeDisplay
GameTeamDisplay
WinningTeamDisplay
PickedTeamAbbr
OK, so here is the insanity that doesn't work. I can get my table headers created successfully, but then the tbody isn't working, but it's erroring in an odd place.
I had to put all the #Html.Raw(...) stuff in there because it was having trouble finding the end tags for the foreach and if statements without them.
Anyway, here is my code. The line that is causing the exception is this:
#gameID = #pick.Game.GameID;
The exception is --> Compiler Error Message: CS1525: Invalid expression term '='
The intellisense shows #gameID as a variable and the #pick.Game.GameID seems to be correct as well.
<table>
<thead>
<tr>
<th>Game</th>
<th>Game Date/Time</th>
<th>Winner</th>
#foreach(var name in #Model.UserNames) {
<th>#name</th>
}
</tr>
</thead>
<tbody>
#{
int lastGameID = 0;
int gameID = 0;
bool firstGame = true;
}
#foreach(var pick in #Model.Picks) {
#gameID = #pick.Game.GameID;
if(#gameID != #lastGameID) {
if(!#firstGame){
<text>#Html.Raw("</tr>")</text>
}
#Html.Raw(
<tr>
<td>#pick.GameTeamDisplay</td>
<td>#pick.GameDateTimeDisplay</td>
<td>#pick.Game.WinningTeam.TeamAbbr</td>
<td>#pick.PickedTeamAbbr</td>
)
}
else {
#Html.Raw(<td>#pick.PickedTeamAbbr</td>)
}
}
#Html.Raw(</tr>)
</tbody>
</table>
UPDATE:
I've removed the #Html.Raw, , etc... Also wrapped the gameID assignment in a #{}. It's now giving me an error on this line,
#{gameID = #pick.Game.GameID;}
Compilation Error: CS1501: No overload for method 'Write' takes 0 arguments
Here is the updated Code:
#foreach(var pick in #Model.Picks) {
#{gameID = #pick.Game.GameID;}
if(#gameID != #lastGameID) {
if(!#firstGame){
#:</tr>
}
#:<tr>
<td>#pick.GameTeamDisplay</td>
<td>#pick.GameDateTimeDisplay</td>
<td>#pick.Game.WinningTeam.TeamAbbr</td>
<td>#pick.PickedTeamAbbr</td>
}
else {
<td>#pick.PickedTeamAbbr</td>
}
}
</tr>
You need to surround it with { } to make it a codeblock
#{gameID = pick.Game.GameID;}
Also, you don't need the # inside the foreach/if statements because they're code blocks.
e.g. you could just write:
foreach(var name in Model.UserNames) {
Just write
#foreach(var pick in Model.Picks) {
<tr>
<td>#pick.GameTeamDisplay</td>
<td>#pick.GameDateTimeDisplay</td>
<td>#pick.Game.WinningTeam.TeamAbbr</td>
<td>#pick.PickedTeamAbbr</td>
</tr>
}
You don't need # inside code block. You can use #: instead of <text>, Html.Raw
You can see here Razor syntax reference
I determined that my Razor view code was simply too complex. The real problem was that I was trying to force a view to work with a Model that I had created for another view. I ended up creating a few more models specifically for this view. Code is much cleaner and best of all it works! Here is the code I ended up with.
<table>
<thead>
<tr>
<th>Game</th>
<th>Game Date/Time</th>
<th>Winner</th>
#foreach(var name in #Model.UserNames) {
<th>#name</th>
}
</tr>
</thead>
<tbody>
#foreach(var game in #Model.Games) {
<tr>
<td>#game.GameDescription</td>
<td>#game.GameDisplayDateTime</td>
<td>#game.GameWinner</td>
#foreach(var pick in game.GamePicks){
<td>#pick.PlayerPick</td>
}
</tr>
}
</tbody>
</table>

Resources