MVC template from folder other than default (EditorTemplates/DisplayTemplates)? - asp.net-mvc

Can you point MVC to a folder other than the default ones (Views/Shared/EditorTemplates & Views/Shared/DisplayTemplates)? I'd like to either put them in subfolders below those, or in other folders outside the Shared folder.
For example, if I have an editor template under this folder:
~\Views\Order\ProductModel.cshtml
How can I tell my EditorFor template to use this tempalte name?
I tried fully qualifying it, but this doesn't work:
#Html.EditorFor(m => m.ProductModel, #"~\Views\Order\ProductModel.cshtml")
I've tried using forward slashes & backslashes, with/without .chstml, every combination I can think of. I'm beginning to think this isn't supported, but I can't imagine why it wouldn't be.

No, I am afraid you can't do this.
For example, if I have an editor template under this folder
That's no longer an editor template. It's a partial. If you want to share editor templates between different controllers you can simply put them inside the ~/Views/Shared/EditorTemplates folder.
As far as subfolders are concerned then you could do this:
#Html.EditorFor(x => x.Foo, "Order/ProductModel")
which will render the ~/Views/CurrentController/EditorTemplates/Order/ProductModel.cshtml or ~/Views/Shared/EditorTemplates/Order/ProductModel.cshtml editor template.

Old question, but... proper way to add display/editor template for specific controller is to add it in DisplayTemplates or EditorTemplates subfolder.
Assuming that, in your example, you have OrderController, you can simply put display template for your model into sub-folder, like this:
~\Views\Order\DisplayTemplates\ProductModel.cshtml
Then, call display template normally from your view (ex: from `~\Views\Order\Index.cshtml):
#Html.DisplayFor(m => m.MyProductModelProperty)

If you do this:
#Html.EditorFor(x => x.Foo, "Order/ProductModel")
it won't parse Foo as a collection and apply your editor template to each item. It will rather assume that your editor template should be applied to the collection as a whole.
If you want to apply editor template to each item individually, just place it in EditorTemplates folder under your view folder (as it will have precedence) and use the default syntax:
#Html.EditorFor(x => x.Foo)
Of course, the name of the editor template has to match the type of items in your collection.

Related

Html.RenderPartial - Render Partial View located in another folder

I have my view 'Create.cshtml' in folder Views-Department. I want to use partial view which is located in folder on root, 'CommonViews' with the name '_EnterpriseStructure.cshtml'.
I am using syntax RenderPartial
#{Html.RenderPartial("~/CommonViews/_EnterpriseStructure.cshtml");}
Partial view code
<div id="Client">
This is a Partial View.
</div>
When executed I am getting System.InvalidOperationException.
Detail error is:
The view at '~/CommonViews/_EnterpriseStructure.cshtml' must derive from WebViewPage, or WebViewPage.
I am using ASP.Net MVC 5 Razor Views
I have found that Razor view engine is searching in folders 'Views/Shared', 'Views/Departments' . When I moved the Partial View, to folder 'Shared' it worked.
You cannot include path, you just have to give View name. And add folders to search for View engine.
What I cannot figure out is "How to give more Search locations to View Engine?"
I would reckon you to use T4MVC nuget package in your MVC project. Once the package is included in your project, you just need to select "T4MVC.tt" file in your project (solution explorer) and say "Run Custom Tool". That's it. This will create constants for almost everything in your MVC project. That means, all views, controllers, actions, javascript files, resources, css files, images, etc are now having constants.. This way you can avoid using the hard-coded strings for views etc in your methods, and can use constants generated by T4MVC. You won't need to worry about path of views etc. T4MVC is very effective and is must for MVC projects.

Kendo editor templates is not found when placing inside an area

We're using Kendo grid with Editor templates. In the examples provided by Kendo they store the templates in the global Shared folder for all Views: ~/Views/Shared/EditorTemplates.
In our project we use Areas and it is more appropriate and logical to store the templates in a Shared folder of particular Area and Controller. However, the template cannot be found if we store it inside an area.
We tried several variations of the structures:
~/Areas/SomeArea/Views/SomeView/Shared/EditorTemplates/editor.cshtml
~/Areas/SomeArea/Views/SomeView/EditorTemplates/editor.cshtml
And the corresponding path in the grid:
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("/Shared/Editortemplate/editor")
or
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("/Editortemplate/editor")
However, instead of our template the default one appears.
Where do we do this wrong? Thanks!
The name passed to the TemplateName method should be just the name of the template not the whole path, in your case it should be "editor". Rest of the work how this template will be found will be done by the Razor ViewEngine.
I would suggest you to check the following question which is pretty similar. I hope it helps.

Using components in admin-generator modules, it's possible? how?

I need to build a admin interface like this image show. In the past I use components for that purpose but now because the modules are generated trough admin-generator I don't know how to get this done. I check all this docs 1, 2, 3 but without any clue on how to do this. I also created a components.class.php under modules/sdriving_empresa/actions folder and include the component in the view include_component('sdriving_empresa') but get this error:
sfComponents initialization failed.
Any help?
Tabs and Partials, the easy way :)
One of the best possible javascripts for that purpose is Javascript Tabifier. Its easy
to install and play with it. You will find a lot of other Javascript and jQuery Tabbers, get the one you most like.
I would advise you to learn everything about symfony 1 partials in order to get the job easily done. Usually partials are a piece of code which is saved in an external file, and does is loaded later in any part of your code. Its like a variable with a lot of html and php code. Partials (the external files) allow also to receive input variables, so its easy to send them ids from related modules or tables.
Lets look at an example with Tabifier with two Tabs, information and Admin and two partials
editSuccess.php
$sModuleName = sfContext::getInstance()->getModuleName();
$sbasepathtabs = $sModuleName . '/tabs';
<div class='tabber' id='tabberglobal1'>
<div class='tabbertab' title='Information' >
<?php
include_partial($sbasepathtabs . '/_information/_information', array('form' => $form));
?>
</div>
<div class="tabbertab" title="Admin" >
<?php
include_partial($sbasepathtabs . '/_admin/_admin', array('form' => $form));
?>
</div>
</div>
Easily setup it:
Inside your module template folder, create the folder: /_tabs
Inside the folder /_tabs create the folder /_information and /_admin
Inside the folder /_tabs/_information create the file partial: _information.php
Inside the folder /_tabs/_admin create the file partial: _admin.php
Inside each one of those files partials write anything you want.
Those partials will receive the left variable form: array('form' => $form).
You can send to the partials more than one variable: array('form' => $form, 'variable2' => $formnumber2)
When you write a partial, in example the partial _information, you can easily get the form object and its values in the template with:
$id = $form->getObject()->getId();
For normal variables you wont need to call getObject.
Finally, take a deep look at the documentation of both things, symfony partials and Javascript Tabifier. They will solve you anything you need.
Backend Admin Generator:
Admin generator automatically generates all templates in the cache folder. Example:
cache\backend\prod\modules\autoTbPrueba1Backend\templates
cache\backend\prod\modules\autoTbPrueba1Backend\templates\indexSuccess.php
Most of its files are already partials, pay attention to the files who has the _ symbol in their name, they are partials. This means that most of the work is already done for you, and the only thing you will have to do is to override some of the partials (TbPrueba1Backend/list_header which is the file _list_header.php) or even the full template (indexSuccess.php) with the extended information you need.
In order to override backend generated templates and partials, you can copy those files to the template folder of your module:
apps\backend\modules\TbPrueba1Backend\templates
apps\backend\modules\TbPrueba1Backend\templates\indexSuccess.php
Set there any additional information you need, and if you dont see anything new while refreshing the web, remember to clear the symfony cache (symfony cc).
Once you have override the the templates and partials with the new information, the only thing you need now is to write/add those partials inside the div tabs created by your bootstrap framework as I described above.
For a good explanation of the admin generator:
Symfony 1.4 change admin generator actions or templates
http://www.slideshare.net/loalf/symfony-y-admin-generator
http://symfony.com/legacy/doc/jobeet/1_4/en/12?orm=Doctrine
You need the moduleName and the componentName in your include_component()
function include_component($moduleName, $componentName, $vars = array())
{
echo get_component($moduleName, $componentName, $vars);
}
Or maybe your module is in the wrong application. In that case, you may consider moving it in a plugin

MVC Razor helper does not exist in current context

I have created a custom razor helper in my MVC4 Web application that I need to be usable in all of my views.
In all of my view pages, I can't seem to use my custom helper. VS2012 doesn't just see it.
How Can I resolve this please ?
EDIT: It actually works when I run the page, it's just VS that doesn't see it.
Here is my helper which is located in Helpers.cshtml within my AppCode folder.
#helper TextBox(string title, string id, string placeholder, bool required){
<ul>
<li>
<label for="#id">#title</label>
</li>
<li>
<input type="text" name="this" class="#if (#required) {<text>required</text>}" minlength="2" id="#id" placeholder="#placeholder" />
</li>
</ul>
}
Restart Visual Studio
Clean and rebuild alone was not enough but the steps that worked for me were:
Clean solution
Restart Visual Studio (2012)
Rebuild solution
After those steps, the Visual Studio Intellisense picked it up again.
Try to build/rebuild the project (if your helper is in the App_Code folder).
Then VS will recognize the helper.
If it is razor helper(using #helper syntax), you should define it in view placed within \App_Code
We can accomplish this by saving our #helper methods within
.cshtml/.vbhtml files that are placed within a \App_Code directory
that you create at the root of a project. For example, below I
created a “ScottGu.cshtml” file within the \App_Code folder, and
defined two separate helper methods within the file (you can have any
number of helper methods within each file):
And if it is more traditional html helper, you should reference it, by adding record to namespaces element of <system.web.webPages.razor> defined in ~\Views\Web.Config. If you want to use it only in singe view, you could add #using directive on top of view.
In any view you could call your custom Razor helper like this:
#Helpers.TextBox("some title", "someid", "default value", false)
This assumes that your helper is defined inside ~/App_Code/Helpers.cshtml.

.Net MVC replacement for Formtastic

I've found myself working on a .Net MVC3 project and sorely missing having Formtastic available in my rails apps.
Are there any good .Net MVC replacements for Formtastic?
I suggest using MVC3s HTML Helpers.
#model mynspace.MyModel
#Html.EditorForModel()
This html helper generates editor fields for every field in your model, choosing the most likely option. Editing the Editor template, you can change the way it is layed out as well. See this question on changing the template
It can of course be used more customizable by each field with things like:
#Html.Label("Daily Rate")
#Html.EditorFor(model => model.DailyRate)
#Html.ValidationMessageFor(model => model.DailyRate, "Please enter a valid Daily Rate (2 d.p.)")
This can be custom layed out by putting tags around it, i.e. things like <p> or <td>
You can also force an input type using options like:
#Html.TextBoxFor(model => model.DailyRate)
#Html.CheckBoxFor(model => model.DailyRate)
#Html.DropDownBoxFor(model => model.DailyRate, ViewBag.DailyRates)
see here for a full list of options
I have a project called FormFactory that lets you do much of the stuff formastic does http://formfactory.apphb.com/
It transforms model objects into PropertyVm objects, which are a viewmodel for an input basically. You could manually create the PropertyVms if you want.

Resources