EditorTemplates are great since they allow some kind of "polymorphism" in razor views. But I am missing one "brick" to complete the polymorphism support:
Can an EditorTemplate for a special type inherit from the EditorTemplate for the general type?
Long version:
Given
class SpecialChild : GeneralChild { }
class Parent
{
GeneralChild AGeneralChild { get; set; }
SpecialChild ASpecialChild { get; set; }
}
and two editor templates
#* GeneralChild.cshtml *#
#model GeneralChild
<span>GeneralChild</span>
#* SpecialChild.cshtml *#
#model SpecialChild
<span>SpecialChild is a</span> <span>GeneralChild</span>
What I get (which is why I call it "polymorphism") is:
#* Index.cshtml *#
#Html.EditorFor(m => m.AGeneralChild)
// prints "<span>GeneralChild</span>", however
#Html.EditorFor(m => m.ASpecialChild)
// prints "<span>SpecialChild is a</span> <span>GeneralChild</span>"
That is, even though SpecialChild is a GeneralChild and there is a template for GeneralChild, it auto-selects the SpecialChild.cshtml template. Furthermore, if I remove that template, it falls back to the GeneralChild.cshtml template. In other words, it is possible to reuse a general template or to override it if necessary.
Now for what I would really like:
I would like to reuse the GeneralChild.cshtml template to define the SpecialChild.cshtml template, like a "base method" call in C#. In pseudo-code:
#* SpecialChild.cshtml *#
baseEditorFor()
#section SpecificPart
{
<span>SpecialChild is a </span>
}
#* GeneralChild.cshtml *#
#Html.RenderSection("SpecificPart") <span>GeneralChild</span>
Is something like that supported?
What I have tried so far:
GeneralChild.cshtml:
#model GeneralChild
#{
var extend = ViewData.ContainsKey("Extend")
? (MvcHtmlString)ViewData["Extend"]
: null;
}
#if (extend != null) { #extend }
<span>GeneralChild</span>
SpecificChild.cshtml:
#model SpecialChild
#Html.EditorFor(
m => m, // call editor for my model
"GeneralChild", // but call "base" instead of "this"
new
{
// Hand the HTML to insert as ViewData parameter
Extend = new MvcHtmlString("<span>SpecialChild is a </span>")
})
Unfortunately, #Html.EditorFor(m => m) does not do anything. That makes sense because m => m is not the same expression as the original m => m.ASpecialChild.
I thought I could build up the expression tree by hand, but then I realized that the type arguments within the editor template are (of course) different from the ones in the Index.cshtml. #Html in the original call is typed <Parent> whereas within the template it is <SpecialChild>.
Then I tried another approach which is the closest I got so far:
Within the Index.cshtml I define a razor helper:
#helper SpecialChildEditorFor(Expression<Func<Parent,SpecialChild>> expression)
{
#Html.EditorFor(
expression,
"GeneralChild",
new { Extend = new MvcHtmlString("<span>SpecialChild is a </span>") })
}
Then I call this instead of EditorFor:
#SpecialChildEditorFor(m => m.ASpecialChild)
But of course this lacks the entirety of the the initially mentioned advantages - I can't simply drop this snippet in the EditorTemplates directory, thus "overriding" the GeneralChild.cshtml template. Also, it needs to be explicitly called (so we lost "polymorphism", too). Even more, the razor helper is tied to the Index.cshtml page:
* It has to be defined within the page where it is used.
* It relies on expression to have the same type arguments as the one the page needs.
Use Partial in editor template insted of #Html.EditorFor(m => m, ...):
#model SpecialChild
#{
ViewData["Extend"] = new MvcHtmlString("<span>SpecialChild is a </span>");
}
#Html.Partial("~/Views/Shared/EditorTemplates/GeneralChild.cshtml", Model)
Related
I have the following form:
#using (Html.BeginForm("Cancel", "Member", FormMethod.Post))
{
Html.SubmitButton(); //doesn't work
}
#*#Html.SubmitButton(); //does work*#
The extension method looks like this:
public static MvcHtmlString SubmitButton(this HtmlHelper helper)
{
return new MvcHtmlString("<input type = \"submit\" value = \"Cancel\" />");
}
Why is the input element HTML able to be generated outside the using block but not inside it?
You missing the leading # which tells razor to output the results to the view. When you use just Html.SubmitButton();, the method is executed and the result is returned, but nothing is done with it.
Your code needs to be
#using (Html.BeginForm("Cancel", "Member", FormMethod.Post))
{
#Html.SubmitButton()
}
I am trying to call IEnumerable method in my _Layout.cshtml file. At the final I was adviced to "use html.action - to call server method that populates collection and returns partial view".
Currently I have created partial file _Dodatki.cshtml, that contains call of IEnumerable method (Aktualnosci.cs is model file):
#model IEnumerable<DluzynaSzkola.Models.Aktualnosci>
In my _Layout.cshtml I called method from my constructor with:
#Html.Action("_Dodatki", "AktualnosciController ", new {area="" })
And at the final I want to create method in my AktualnosciConstructor.cs file. Currenly I have method:
[ChildActionOnly]
[ActionName("_Dodatki")]
public ActionResult Dodatki()
{
IList<Aktualnosci> lista = new IList<Aktualnosci>();
return PartialView("_Dodatki", lista);
}
Unfortunately, when using syntax as above, it gives me message in compiler:
"cannot create an instance of the abstract class or interface
'IList'".
When replacing 'IList' with 'List', it gives me exception:
"System.Web.HttpException: The controller for path '/' was not found
or does not implement IController."
I have no idea how in other way I can populate collection in the method.
edit: As per request, below AktualnosciController.cs definition, with no other methods:
namespace DluzynaSzkola.Controllers
{
public class AktualnosciController : Controller
{
//here are other methods
[ChildActionOnly]
[ActionName("_Dodatki")]
public ActionResult Dodatki()
{
IList<Aktualnosci> lista = new IList<Aktualnosci>();
return PartialView("_Dodatki", lista);
}
}
}
as noticed by GTown-Coder your controller name seems wrong. Updated my answer accordingly.
I think that your problem might be the same as answered by this SO post.
try specifying the Area name and, if this controller is not in an area simply add an empty area name.
#Html.Action("_Dodatki", "AktualnosciController ", new {area="" })
Even if this does not solve your problem it is good practice because if this view is latter used within an area it will try to find the controller in the area and not in the root space.
Allright, I have implemented changes to my project, that works fine.
My in _Layout.cshtml call is changed a bit. AktualnosciController supposed to be called just Aktualnosci !!!
<div class="kontenerDodatkiLayout hidden-xs hidden-sm">
<div class="archiwum">Archiwum</div>
#Html.Action("_Dodatki", "Aktualnosci", new { area = "" })
</div>
My partial view _Dodatki.cshtml model call is changed a bit:
#model IEnumerable<DateTime>
<div class="wpisDodatki">
#foreach (var item in Model)
{
<div> #Html.DisplayFor(modelItem => item)</div>
}
<p>test<br />test<br />test</p>
</div>
And method in my controller AktualnosciController.cs looks like that:
//[ChildActionOnly]
[ActionName("_Dodatki")]
public ActionResult Dodatki()
{
using (var context = new DluzynaContext())
{
var lista = context.Indeks.Select(it => it.Dzien).ToList();
return PartialView("_Dodatki", lista);
}
}
in here lista is passed to my partial view _Dodatki, and it is populated with context property Indeks and model property Dzien.
Thanks guys for your help #Wndrr , #GTown-Coder.
I have an Item class. I have around 10-20 derivatives of it each containing different types of data. Now when it comes to rendering different types of Item, I'm forced to use likes of:
<div>
#if (Model is XItem)
{
... rendering logic 1 ...
}
#if (Model is YItem)
{
... rendering logic 2 ...
}
#if (Model is ZItem)
{
... rendering logic 3 ...
}
... goes on and on forever ...
</div>
Unfortunately #Html.DisplayFor() does not work in this case because the Model is type of Item, DisplayTemplates\Item.cshtml is displayed.
HTML helpers don't help either because of the same "if/is" chain.
I could incorporate rendering logic inside the classes themselves, and call #Model.Render() but they belong to business logic, not presentation. It would be a sin.
There is only one option of #Html.Partial(Model.GetType().Name) but it feels wrong. You expect a solution without meta-magic. Is there a better way?
Use Display Templates.
Inside your ~/Views/Shared/DisplayTemplates folder you can add a view with the same name as your type.
When you do #Html.DisplayFor(item) you'll get the view related to that specific type.
UPDATE
I just saw your comment RE DisplayFor so if this doesn't help i'll remove my answer.
I think your approach is fine. You can make it better with an extension method like this:
public static MvcHtmlString GetTypePartial<T>(this HtmlHelper htmlHelper, T model, string viewPrefix = "")
{
string typeName = typeof (T).Name;
string viewName = string.Concat(viewPrefix, typeName);
return htmlHelper.Partial(viewName, model);
}
In a MVC 3 application i need to be able to part creation view in 2 different parts, because of some folder creation logic.On first view i have a textbox with Project Name, on click of next button i need to create folder for that project, and i need a way to get that project name folder on my next view in some way. Right now i press next and i loose project Name, and i cant get it again.
On internet there are plenty of places where they implement it the same way, but i cant figure out how to do that.
Any solutions on how to presist model?
You could use a hidden field in the second view that will contain the project name that was entered in the first view. That way when you submit this second form you will get the project name and the project folder.
Another possibility is to store the value that was entered in the first view somewhere on the server (database, session, ...)
UPDATE:
As request in the comments section here's an example using a hidden field.
First view:
#model FirstStepViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.ProjectName)
<button type="submit">OK</button>
}
then a controller action to which this first step will be submitted:
[HttpPost]
public ActionResult Foo(FirstStepViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Bar", new { projectname = model.ProjectName });
}
and then you will have a second controller action that will serve the second view:
public ActionResult Bar(FirstStepViewModel firstStep)
{
var model = new SecondStepViewModel
{
ProjectName = firstStep.ProjectName
};
return View(model);
}
you will then have a corresponding view:
#model SecondStepViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(x => x.ProjectName)
#Html.EditorFor(x => x.ProjectFolder)
<button type="submit">OK</button>
}
which will post to the final action:
[HttpPost]
public ActionResult Bar(SecondStepViewModel model)
{
// here you will get both model.ProjectName and model.ProjectFolder
...
}
You could also load all parts of the form at once, and then use a tabbed layout (e.g., jQuery UI Tabs) and submit the entire form at the last step.
In my code:
#foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
i have an excepion on RenderPartial line.
error CS1513: } expected.
What am I doing wrong?
For completeness, here's another way of causing this:
#if(condition)
{
<input type="hidden" value="#value">
}
The problem is that the unclosed element makes it not obvious enough that the content is an html block (but we aren't always doing xhtml, right?).
In this scenario, you can use:
#if(condition)
{
#:<input type="hidden" value="#value">
}
or
#if(condition)
{
<text><input type="hidden" value="#value"></text>
}
This is basically the same answer that Mark Gravell gave, but I think this one is an easy mistake to make if you have a larger view:
Check the html tags to see where they start and end, and notice razor syntax in between, this is wrong:
#using (Html.BeginForm())
{
<div class="divClass">
#Html.DisplayFor(c => c.SomeProperty)
}
</div>
And this is correct:
#using (Html.BeginForm())
{
<div class="divClass">
#Html.DisplayFor(c => c.SomeProperty)
</div>
}
Again, almost same as the earlier post about unclosed input element, but just beware, I've placed div's wrong plenty of times when changing a view.
MY bad.
I've got an error in the partial view.
I've written 'class' instead of '#class' in htmlAttributes.
I've gotten this issue with Razor. I'm not sure if it's a bug in the parser or what, but the way I've solved it is to break up the:
#using(Html.BeginForm()) {
<h1>Example</h1>
#foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
}
into:
#{ Html.BeginForm(); }
<h1>Example</h1>
#foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
#{ Html.EndForm(); }
The Razor parser of MVC4 is different from MVC3. Razor v3 is having advanced parser features and on the other hand strict parsing compare to MVC3.
--> Avoid using server blocks in views unless there is variable declaration section.
Don’t : \n
#{if(check){body}}
Recommended :
#if(check){body}
--> Avoid using # when you are already in server scope.
Don’t : #if(#variable)
Recommended : #if(variable)
Don't : #{int a = #Model.Property }
Recommended : #{int a = Model.Property }
Refrence : https://code-examples.net/en/q/c3767f