Rendering a spark view to a string - asp.net

I'm trying to render a partial view as a string so it can be returned as HTML to a jquery ajax call. After a lot of searching I found this code.
public string RenderAsString(string viewName, string modelName, object model)
{
// Set up your spark engine goodness.
var settings = new SparkSettings().SetPageBaseType(typeof(SparkView));
var templates = new FileSystemViewFolder(Server.MapPath("~/Views"));
var engine = new SparkViewEngine(settings) { ViewFolder = templates };
// "Describe" the view (the template, it is a template after all), and its details.
var descriptor = new SparkViewDescriptor().AddTemplate(#"Shared\" + viewName + ".spark");
// Create a spark view engine instance
var view = (SparkView)engine.CreateInstance(descriptor);
// Add the model to the view data for the view to use.
view.ViewData[modelName] = model;
// Render the view to a text writer.
var writer = new StringWriter(); view.RenderView(writer);
// Convert to string
return writer.ToString();
}
But when the following line executes:
var view = (SparkView)engine.CreateInstance(descriptor);
I get the following error:
Dynamic view compilation failed. An
object reference is required for the
non-static field, method, or property
'DomainModel.Entities.Region.Id.get.
This is my partial view:
<ViewData Model="Region" />
<div id="${ Region.Id }" class="active-translation-region-widget" >
<label>${Region.RegionName}</label>
${ Html.CheckBox("Active") }
</div>
It doesn't seem to recognise the model.
P.S. When I call the view from a parent view like so
<for each="var region in Model">
<ActiveTranslationRegion Region="region" if="region.Active==true"></ActiveTranslationRegion>
</for>
It renders perfectly. What am I doing wrong?

Just from looking at it, I think the following line is the problem:
<ViewData Model="Region" />
Instead it should read:
<viewata model="Region" />
Note the lower case "model". This is because model is a special case since behind the scenes it performs a cast to a strongly typed viewmodel. The top one will define a variable called Model in the generated view class and assign the value Region to it. Using the lowercase option below will actually create a Model variable, but also cast it to strongly typed instance of Region that comes from the ViewData dictionary.
Note When using Model in the code though, like you did in the for each loop, it needs to be upper case which is correct in your case. Once again, this is the only special case because it's pulling a strongly typed model from the ViewData dictionary.
One other thing - <viewata model="Region" /> must be declared in the parent view, and it can only be defined once per page, so you cannot redefine it in a partial view. If it's a partial view, you should rather use it by passing in a part of the model like you have done in your second example above.
The reason for your exception above is because it's trying to get the Id property as a static item off the Region Type, rather than querying the Id property on your instance of Region as part of your viewmodel.
As a side note, the code to get where you want is a little mangled. You can find neater ways of doing what you want by checking out some of the Direct Usage Samples, but I understand this was probably just a spike to see it working... :)
Update in response to your follow up question/answer
I'm fairly sure that the problem is with passing the Region into the following call:
<ActiveTranslationRegion Region="region" if="region.Active==true">
... is again down to naming. Yes, you can only have one model per view as I said before, so what you need to do is remove the following from the top of your partial:
<viewdata model="Region" />
That's what's causing an issue. I would then rename the item going into your partial like so:
<ActiveTranslationRegion ActiveRegion="region" if="region.Active==true">
and then your partial would look like this:
<form action="/Translation/DeactivateRegion" class="ui-widget-content active-translation-region-widget">
<input type="hidden" name="Id" value="${ActiveRegion.Id}" />
<label class="region-name">${ ActiveRegion.RegionName }</label>
<input class="deactivate-region-button" type="image" src=${Url.Content("~/Content/Images/Deactivate.png")} alt="Deactivate" />
</form>
Note I'm using ActiveRegion because in the Spark parser, ActiveRegion gets declared as a variable and assigned the value of region in the current scope as you loop through the for loop. No need to stick religiously to the model - because you've gone and passed in a piece of the model now that you've declared as ActiveRegion. Oh, and you could stick with the name Region if you really want, I just changed it to make a point, and because you've got a Type called Region in your code and I'm not a big fan of the quirky issues using the same name for a variable as a type can bring about. Plus it makes it a little clearer.
The disadvantage of calling the Html.RenderPartial method is not immediately obvious. One thing you lose is the 3-pass rendering that Spark provides. If you use the tag syntax (which is preferable) you'll be able to stack partials within partials to multiple levels down passing variables that feed each partial what they need down the stack. It gets really powerful - start thinking data grid type structures where rows and cells are individual partials that are fed the variables they need from the model, all kept nice and clean in separate manageable view files. Don't stop there though, start thinking about targeting header and footer content base on variables or three column layouts that create a dashboard that renders all sorts on individually stacked partials many levels deep.
You lose all of that flexibility when you use the bog standard ASP.NET MVC Helper method Html.RenderPartial() - careful of doing that, there's more than likely a solution like the one above.
Let me know if that works...
All the best
Rob G

I refactored the code and views quite a bit. In the end all I'm really trying to acheive is have a parent view (not shown) iterate over an IEnumerable and for each iteration render a partial view (ActiveTranslationRegion) which renders some Html to represent a region model.
I also want to be a able to call an action method via an ajax call to render an indivual ActiveTranslationRegion partial view by passing it an individual region model. I've refactored the code accordingly.
Partial view (_ActiveTranslationRegion.spark)
<viewdata model="Region" />
<form action="/Translation/DeactivateRegion" class="ui-widget-content active-translation-region-widget">
<input type="hidden" name="Id" value="${Model.Id}" />
<label class="region-name">${ Model.RegionName }</label>
<input class="deactivate-region-button" type="image" src=${Url.Content("~/Content/Images/Deactivate.png")} alt="Deactivate" />
</form>
Notice by using I can refer to Model within the view as RobertTheGrey suggested (see above) .
I removed all the code to return the view as a string and simply created an action method method that returned a partialViewResult:
[UnitOfWork]
public PartialViewResult ActivateRegion(int id)
{
var region = _repos.Get(id);
if (region != null)
{
region.Active = true;
_repos.SaveOrUpdate(region);
}
return PartialView("_ActiveTranslationRegion", region);
}
One thing I had to do was amend my parent view to look like so:
<div id="inactive-translation-regions-panel">
<h3 class="ui-widget-header">Inactive Regions</h3>
<for each="var region in Model">
<span if="region.Active==false">
# Html.RenderPartial("_InActiveTranslationRegion", region);
</span>
</for>
</div>
Where previously I had the following:
<div id="inactive-translation-regions-panel">
<for each="var region in Model">
<ActiveTranslationRegion Region="region" if="region.Active==true"></ActiveTranslationRegion>
</for>
</div>
Notice I have to call the Html.RenderPartial rather than use the element. If I try and use the element (which I would prefer to do) I get the following error:
Only one viewdata model can be declared. IEnumerable<Region> != Region
Is there a way round that problem?
Update:
I tried your recommendation but with no luck. To recap the problem, I want to use the partial in 2 different situations. In the first instance I have a parent view that uses a model of IEnumerable<Region>, the partial simply uses Region as its model. So in the parent I iterate over the IEnumerable and pass Region to the partial. In the second instance I want to call PartialView("_ActiveTranslationRegion", region) from an action method. If I remove the <viewdata model="Region" /> from the partial I get an error complaining about the model. The best way round the problem I have found is to add a binding to the bindings.xml file:
<element name="partial"># Html.RenderPartial("#name", #model);</element>
(Note: It seems very important to keep this entry in the bindings file all on te same line)
This way I can still call the partial from the action method as described above and pass it a Region as the model, but I can also replace my call to Html.RenderPartial in the parent view with a more 'html' like tag:
<partial name="_ActiveTranslationRegion" model="region" />
So my parent view now looks more like this:
<div id="inactive-translation-regions-panel">
<h3 class="ui-widget-header">Inactive Regions</h3>
<for each="var region in Model">
<span if="region.Active==false">
<partial name="_ActiveTranslationRegion" model="region" />
</span>
</for>
</div>
Of course under the hood its still making a call to
# Html.RenderPartial("_ActiveTranslationRegion", region);
But its the best solution we could come up with.
Regards,
Simon

Related

Controller does not receive value from view (implementing search function) on MVC

I'm trying to make a page with a search function. When you first go to the page, all you have is a search bar. When you type something into the search bar and click the "submit" or "search" button, I want the value in the search box to be submitted to the controller as a string. Then, this value can be used in returning the a model back to the page. Here's what I have so far:
Search.cshtml
#{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#ViewBag.PageTitle
<h1>Search All Issues</h1>
<form asp-controller="Report" asp-action="Search" method="get">
<input name="searchstr" id="Search" />
<input type="submit" value="Submit" />
</form>
ReportController.cs
[HttpGet]
public ActionResult Search(string test)
{
ViewBag.PageTitle = test;
var report = _context.Reports.ToList();
return View(report);
}
What am I doing wrong here? For now, it would be nice if I can just get that ViewBag.PageTitle to appear on the page. If I can do that, then I can return the report model just the way I want.
Also, a few additional questions. Some of the stuff I've seen on stack overflow has a recommendation to do a Post in the controller. If I do that, the page errors out. Why is a get needed for this? Intuitively, it makes more sense to me to use a Post...
Turns out I was extremely close; Stephen Muecke had the correct answer. I simply needed to change my input name or parameter name.
I made this mistake as I was considering this from a C++/C standpoint where the parameter names can be irrelevant. I see now, though, that with ASP.NET MVC, you need to have the input name match the parameter name.
Thanks for the help!

how to insert partial view from another controller in asp.net mvc 5

I want to insert a partial view from NewsController into HomeController.
In my NewsController
public ActionResult LastNewsPatial()
{
var lstLastNews = db.Articles.Take(5).OrderByDescending(m => m.CreatedDate).ToList();
return PartialView(lstLastNews);
}
In Views/News folder i create LastNewsPatial.cshtml
#model IEnumerable<mytest.com.Models.Article>
#foreach (var item in Model) {
<div class="glidecontent">
<img src="#item.ImageURL" style="float: left; margin-right:21px;" />
<strong>#item.Title</strong><br /><br />
#item.Content
</div>
}
In Views/Home/Index.cshtml i insert a LastNewsPatial view
#Html.Partial("~/Views/News/LastNewsPatial.cshtml")
When i run my project then I received a error
Object reference not set to an instance of an object.
at row
#foreach (var item in Model)
in LastNewsPatial.cshtml
How can I fix it?
The reason for your error is that the Model isn't passed to the view... infact the action isn't even called at all. Set a breakpoint and you'll confirm this.
I think you should be calling #Html.RenderAction inside the index instead of #Html.Partial.
Instead of #Html.Partial("~/Views/News/LastNewsPatial.cshtml")
use
#Html.RenderAction("LastNewsPatial","News")
or #Html.Action("LastNewsPatial","News")
You don't need to give .cshtml in name of view when rendering a view. Only give name of PartialView without .cshtml like this.
#Html.Partial("~/Views/Shared/LastNewsPatial")
You can also use #Html.Action() to render your view like this
#Html.Action("LastNewsPatial","News")
This worked for me: #Html.Partial("../Views/Shared/LastNewsPatial")
The .. instead of the ~
Some of the answers here are missing the question
You use this
#Html.Partial("~/Views/News/LastNewsPatial.cshtml")
Which creates a partial view without a model. So in order for this to work you need to pass model.
#Html.Partial("~/Views/News/LastNewsPatial.cshtml", your_model)
Your problem is not view related and you simply pass no object to the partial. How to do it is up to you. Do you want a Html.Partial or Html.Action? Depending on your needs.
P.S.
Use RenderPartial and RederAction they are better practices since Partial and Action return an HTML string where instead using render allows ASP.NET to write directly to the response stream.

How do I pass arguments down to component (Dreamweaver) templates?

I have a page template that outputs three component presentations in a div down the bottom of the page. All three of these component presentations use the same schema and Dreamweaver component template.
I'd like to style these component presentations slightly differently based on whether they're the first component in that div, or the last - basically I'd like to add "first" and "last" CSS classes to each component presentation.
I'm trying to set "arguments" for the component presentations dynamically, in a template building block. Below is what I've got so far (doesn't work, but just to give you an idea of what I'm trying to do):
public override void Transform(Engine engine, Package package)
{
var page = GetPage();
var wantComponents =
from c in page.ComponentPresentations
where c.ComponentTemplate.Title == "Content highlight"
select c;
if (wantComponents.Count() > 0)
{
// pseudocode - won't compile!
wantComponents.First().ComponentTemplate.Parameters["myCssClass"] = "first";
wantComponents.Last().ComponentTemplate.Parameters["myCssClass"] = "last";
}
...
In my Dreamweaver template (again, doesn't work, just to give you an idea of what I'm trying to do):
<div class="block ##Parameters.myCssClass##">
...
</div>
How do I dynamically add the "first" CSS class to the first component presentation on the page, and the "last" CSS class to the last component presentation on the page?
Not a bad question at all George.
If you take your divs out of the Component Template and put them into the Page Template then you don't need to pass the arguments from the Page template into the Component Template. Then setting the CSS class to the first component presentation is easy:
<div class="<!-- TemplateBeginIf cond="TemplateRepeatIndex==0" -->myFirstCssClass<!-- TemplateEndIf -->"></div>
Setting a class on the last Component Presentation is a bit more fun and there are a couple of ways this can be achieved:
A custom Dreamweaver function, for example TemplateRepeatCount(). Then you can do stuff like this inside your Page Template:
<!-- TemplateBeginRepeat name="Components" --><div class="<!-- TemplateBeginIf cond="TemplateRepeatIndex==TemplateRepeatCount()-1" -->lastCssClass<!-- TemplateEndIf -->">##RenderComponentPresentation()##</div><!-- TemplateEndRepeat -->.
The other approach is to write a basic TBB that counts up the component presentations and drops the total number onto the package, and then you can compare your TemplateRepeatIndex against this number.
Both #1 and #2 above are described in my article here: http://www.tridiondeveloper.com/more-fun-with-dreamweaver-templates-templaterepeatcount
Finally, here is an approach more inline with specifically what you were asking where a Component Template actually looks up into the Page's scope to determine if it's the last Component Presentation in the list. It's not my favourite because it's not so easy to debug with TemplateBuilder (since when you're running through a CT you don't have a PT, hence the component presentation count doesn't exist in this scope).
public class IsLastCP : TemplateBase
{
private string MY_SCHEMA = "My Component's Schema Title";
public override void Transform(Engine engine, Package package)
{
this.Initialize(engine, package);
//in the page template.
Page page = this.GetPage();
if (page == null)
{
//this TBB is being executed either in Template Builder or a dynamic component presentation.
// so we just don't do anything.
}
else
{
IList<ComponentPresentation> cpList = page.ComponentPresentations;
int cpCount = 0;
int thisCPIndex = -1;
Component thisComponent = this.GetComponent();
foreach (ComponentPresentation cp in cpList)
{
Component comp = cp.Component;
if (comp.Schema.Title == MY_SCHEMA)
{
if (comp.Id.Equals(thisComponent.Id))
thisCPIndex = cpCount;
cpCount++;
}
}
if (thisCPIndex == cpCount-1)
{
package.PushItem("IsLastCP", package.CreateStringItem(ContentType.Text, "true"));
}
}
}
For this you'll need Will's famous TemplateBase class which you can get from his "Useful Building Blocks" extension available from SDLTridionWorld. Obviously you'll need to tweak the code I provided to your schema name, etc.
Drop this TBB ahead of your Dreamweaver TBB in your Component Template then use its output like this: <!-- TemplateBeginRepeat name="IsLastCP" -->class="myLastCSSClass"<!-- TemplateEndRepeat -->
Note: you don't need to do a TemplateBeginIf here and check explicitly for true/false on IsLastCP. If the CP in question is last, then this variable will be present in the package, and the TemplateBeginRepeat clause will enter.
You can also do this kind of thing using Context Variables. You can't do this directly from a DWT, so this would mean perhaps writing a function source, or perhaps replacing the DWT with an assembly TBB that writes to output. If this kind of approach fits your design you can just write a variable into engine.PublishingContext.RenderContext.ContextVariables from the page template, indicating whether the Component render is the first or not, and then have the component template read it to determine what output to produce.
In general, the idea is to write variables in the page template and read them in component templates. This should be enough to let you avoid moving component template concerns into the page template, although, of course, the amount of plumbing might put you off. For more extreme cases, it's possible to get values from the component template to the page template, but then you've got even more plumbing, so wanting to do that at all might be a design smell.

activating a different <div> with a partial view in my Layout.html by getting the name of controller action or view

I'd like to get the name of my partial view in my layout page to determine which div is going to be active. Because of the design I cannot css this nicely so I went for a more sloppy approach.
In my _Layout.chtml The Renderbody loads my content. And here depending on which button I press, I get a map or a list.
These are both functions in my controller and what I would like to do is get the functionname or partial view so I can then decide which I want to show.
so I wanted to do something like this in my _Layout.chtml
#if ( get the controllername or view == mapname or listname)
{
<div>
#Html.Partial("tabMap")
</div>
}
else
{
<div>
#Html.Partial("tabList")
</div>
}
Any quick fix to do this ?
access the RouteData dictionary from the ViewContext Object
will be like this
#ViewContext.RouteData.Values["Controller"]
with the RouteData Dictionary you can get all the info needed about the controller , action and extra parameters names , depending on them output the data you want

Orchard and master detail editing

I was reading http://www.orchardproject.net/docs/Creating-1-n-and-n-n-relations.ashx and could not get the idea, if it is possible to easily make master detail editing, to give you concrete example i've attached screenshot from wordpress:
So there is post and post contains set of custom fields, simple 1:N relationship, everything edited in one page - you can add/edit custom field without leaving post page.
May be someone saw similar example for Orchard on internet, or could shortly describe path to achieve this by code, would be really helpful (I hope not only for me, because this is quite common case I think).
This should be possible, although not in the most 'Orchardy' way.
I've not tested any of the below so it is probably full of mistakes - but maybe Bertrand or Pszmyd will be along later today to correct me :-)
As you have probably seen you can pass a view model to a view when creating a content shape in your editor driver:
protected override DriverResult Editor(CatPart part, dynamic shapeHelper)
{
// Driver for our cat editor
var viewModel = new CatViewModel
{
Cats = _catService.GetCats() // Cats is IEnumerable<Cat>
};
return ContentShape("Parts_CatPart_Edit",
() => shapeHelper.EditorTemplate(
TemplateName: "Parts/CatPart",
Model: viewModel,
Prefix: Prefix
));
}
So we can pass in a list of items, and render it in our view like so:
#foreach(var cat in Model.Cats)
{
<span class="cat">
<p>#cat.Name</p>
<a href="...">Delete Cat</p>
</span>
}
The problem here would be posting back changes to update the model. Orchard provides an override of the Editor method to handle the postback when a part is edited, and we can revive the viewmodel we passed in the previous method:
protected override DriverResult Editor(CatPart part, IUpdateModel updater, dynamic shapeHelper)
{
var viewModel = new CatViewModel();
if (updater.TryUpdateModel(viewModel, Prefix, null, null))
{
// Access stuff altered in the Cat view model, we can then update the CatPart with this info if needed.
}
}
This works really well for basic information like strings or integers. But I've never been able to get it working with (and not been sure if it is possible to do this with) dynamic lists which are edited on the client side.
One way around this would be to set up the buttons for the items on the N-end of the 1:N relationship such that they post back to an MVC controller. This controller can then update the model and redirect the client back to the editor they came from, showing the updated version of the record. This would require you to consistently set the HTML ID/Name property of elements you add on the client side so that they can be read when the POST request is made to your controller, or create seperate nested forms that submit directly to the contoller.
So your view might become:
#foreach(var cat in Model.Cats)
{
<form action="/My.Module/MyController/MyAction" method="POST">
<input type="hidden" name="cat-id" value="#cat.Id" />
<span class="cat">
<p>#cat.Name</p>
<input type="submit" name="delete" value="Delete Cat" />
</span>
</form>
}
<form action="/My.Module/MyController/AddItem" method="POST">
<input type="hidden" name="part-id" value="<relevant identifier>" />
<input type="submit" name="add" value="Add Cat" />
</form>
Another possibility would be to create a controller that can return the relevant data as XML/JSON and implement this all on the client side with Javascript.
You may need to do some hacking to get this to work on the editor for new records (think creating a content item vs. creating one) as the content item (and all it's parts) don't exist yet.
I hope this all makes sense, let me know if you have any questions :-)

Resources