Nested Display Templates In Razor - asp.net-mvc-3

I'm currently getting to grips with ASP.Net MVC 3 and the Razor templating engine, but I've come across an issue that I can't quite get to grips with - so over to the StackOverflow community to help!
Let's say that I have a View Model hierarchy that looks like this:
public class Foo {
public string FooTitle { get; set; }
[UIHint("BarList")]
public IList<Bar> BarList { get; set; }
}
public class Bar {
public string BarTitle { get; set; }
}
all fairly simple I'm sure you'll agree. To go with this View Model I have the following:
~/Views/Home/Index.cshtml
#model Foo
<h1>#Model.FooTitle</h1>
#Html.DisplayFor(m => m.BarList)
~/Views/Home/DisplayTemplates/BarList.cshtml
#model IEnumerable<Bar>
<div class="bar-list">
#Html.DisplayForModel()
</div>
~/Views/Home/DisplayTemplates/Bar.cshtml
#model Bar
<p>#Model.BarTitle</p>
I would expect to find the contents of Bar.cshtml to be displayed when I execute my View, but the rendering doesn't seem to nest further that BarList.cshtml
What am I doing wrong here?

You don't need the intermediary BarList.cshtml template nor UIHint if you follow the conventions:
public class Foo {
public string FooTitle { get; set; }
public IList<Bar> BarList { get; set; }
}
public class Bar {
public string BarTitle { get; set; }
}
View (~/Views/Home/Index.cshtml):
#model Foo
<h1>#Model.FooTitle</h1>
<div class="bar-list">
#Html.DisplayFor(m => m.BarList)
</div>
Display template (~/Views/Home/DisplayTemplates/Bar.cshtml):
#model Bar
<p>#Model.BarTitle</p>
and the Bar.cshtml template will automatically be rendered for each element of the BarList collection.

I doubt you still have this issue but this is the correct solution
~/Views/Home/DisplayTemplates/BarList.cshtml
#model IEnumerable<Bar>
<div class="bar-list">
#foreach (var bar in Model) {
#Html.DisplayFor(c => bar)
}
</div>

Move all these Display Templates to:
~/Views/Shared/DisplayTemplates/
Edit: What about iterating through each bar?
#model IEnumerable<Bar>
<div class="bar-list">
#foreach (var bar in Model) {
#Html.DisplayForModel(bar)
}
</div>

Related

ASP.Net MVC 6 PartialView model binding confusion

Background
We need to submit model with items. For that purpose, we make this complex model:
public class PaymentViewModel
{
public decimal? Payment { get; set; }
public string Description { get; set; }
public List<SplittedPaymentViewModel> SplittedPayment { get; set; } = new List<SplittedPaymentViewModel>();
}
public class SplittedPaymentViewModel
{
public short SplittedPaymentId { get; set; }
public decimal? Payment { get; set; }
public string Description { get; set; }
}
For rendering html, we this two views, one regular: CreatePayment
#model ZevApp.ViewModels.Record.PaymentViewModel
...
<input class="form-control" asp-for="Payment" type="number" />
<input class="form-control" asp-for="Description" />
...
<div class="panel-body" id="SplittedPayments">
#foreach (var spItem in Model.SplittedPayment)
{
#Html.Partial("SplittedPaymentPartial", spItem);
}
...
</div>
And the other Partial: SplittedPaymentPartial
#model ZevApp.ViewModels.Record.SplittedPaymentViewModel
...
<input class="form-control" asp-for="Payment" type="number" />
<input class="form-control" asp-for="Description" />
...
As you can see, from the first view, we call partial view and pass them item by item form the SplittedPayment list.
Unexpectedly behavior
We run the code but unexpectedly behavior is occur:
Each partial view bind Payment and Description form parent PaymentViewModel, not from a passed item?
Does anybody know what is wrong?
Each view define model at the beginning of the file.
From the controller we return PaymentViewModel, and for a test, there are tree SplittedPaymentViewModels. But we can't see values from the items.
I found that problem was CreatePayment.cshtml (thanks to the people from MVC community). It doesn't provide any information about the spItem expression when invoking the partial view.
var savePrefix = ViewData.TemplateInfo.HtmlFieldPrefix;
for (var i = 0; i < Model.SplittedPayment.Count; i++)
{
ViewData.TemplateInfo.HtmlFieldPrefix = Html.NameFor(m => m.SplittedPayment[i]);
var spItem = Model.SplittedPayment[i];
#Html.Partial("SplittedPaymentPartial", spItem);
ViewData.TemplateInfo.HtmlFieldPrefix = savePrefix;
}
You can find full description on https://github.com/aspnet/Mvc/issues/4106

Razor view dropdown list for a model class in MVC3

I have two model class in MVC3 one for Services which have those properties
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public int ChildOf { get; set; }
It also have a DB table by Entityframework
Another model is Quata which have those properties
public int ID { get; set; }
public string Sender_Name { get; set; }
public string Description { get; set; }
.....
......
public Services Service_ID { get; set; }
It also have a DB table by Entityframework
I want to create a Razor(C#) view (for Quata) where user can send a quata by fill a html form but where i wanna show a dropdown list with Services ID as dropdown value and Services Name as dropdown text which is also come dynamically from the Services DB table .
My question is how i should create that dynamic dropdown list by #Html.DropDownListFor ? and send the selected data from that dropdown list to a Controller ?
Try this
Controller:
public ActionResult Create()
{
var Services = new Services();
Services.Load(); //load services..
ViewBag.ID = new SelectList(Services.ToList(), "Id", "Name");
return View();
}
[HttpPost]
public ActionResult Create(Quata Quata)
{
//save the data
}
A strong Typed View: (Using Razor)
#model Quata
#using (Html.BeginForm()) {
<fieldset>
<legend>Quata</legend>
<div>
#Html.LabelFor(model => model.Service_ID.ID, "Service")
</div>
<div>
#Html.DropDownList("ID", String.Empty)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
take a look at #Html.DropDownListFor
So say your viewmodel has a list of said Services.
Something that may work for you is the following (you may not need a for loop here, editor is supposed to eliminate that, but I had some weird binding issues).
In your top level view which points at your viewmodel (#model Quata, assuming Quata is your viewmodel) have this code :
#For i = 0 To Model.DropdownListInput.Count - 1
Dim iterator = i
#Html.EditorFor(Function(x) x.DropdownListInput(iterator), "EnumInput")
Next
In your Editor Template (create a subfolder under the view folder this dropdownlist will be in called editor templates and name the template whatever you desire, mine was EnumInput).
In your editor template, which should point at your model for Services (#model Services) have something like the following code (with substitutions for your appropriate variable names):
#<div class="editor-label">
#Html.LabelFor(Function(v) v.value, Model.DisplayName)
</div>
#<div class="editor-field">
#Html.DropDownListFor(Function(v) v.value, New SelectList(Model.ParamEnums, "ValueForScript", "EnumValue"), "--Please Select A Value--")
#Html.ValidationMessageFor(Function(v) v.value)
</div>
Replace the list with your list and the lambda values with yours (#Html.DropDownListFor(x => x.id, New SelectList(x.ServiceList, "ID", "Name"), "--Please Select A Value--") or something like that.
Note that this code is in VB, but it should provide a rough guide.

Inconvenient render partial view MVC 3

I have a partial view of work with a viewmodel, but I have a inconvenience when rendering a partial view in the main view
I get the following message:
The model item passed into the dictionary is of type ‘RolMVC3.Models.USER’ but this dictionary requires a model item of type ‘RolMVC3.Areas. Distributor.Models. LocationViewModel ‘
View Model(LocationViewModel), the ViewModel is within an Area
namespace RolMVC3.Areas.Distributor.Models
{
public class LocationViewModel
{
[Required]
public decimal IdDepartment { get; set; }
[Required]
public string NameCity { get; set; }
[Required]
public string NameNeighborhood { get; set; }
}
}
}
Partial View(_LocationEdit):
#model RolMVC3.Areas.Distributor.Models.LocationViewModel
.....
.....
<div class="editor-label">
#Html.LabelFor(model => model.IdDepartment)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.IdDepartment, new SelectList(ViewBag.Department as System.Collections.IEnumerable, "IdDepartment", "NameDepartment", ViewBag.selectedDepartment), "--- Select ---", new { id = "Department"})
#Html.ValidationMessageFor(model => model.Idepartment)
</div>
.....
.....
Main View(Edit):
#model RolMVC3.Models.USER
#{
ViewBag.Title = "Edit User";
}
....
....
#{Html.RenderPartial("_LocationEdit");}
....
....
How I can resolve this?
Blessings
In your Main View(Edit) pass the LocationViewModel , because partial view requires this model and you are not passing it in #Html.RenderPartial
#model RolMVC3.Models.USER
#{
ViewBag.Title = "Edit User";
}
....
....
#{Html.RenderPartial("_LocationEdit",YourLocationViewMODEL);}
....
....
When you call your RenderPartial you need to pass in a model type of LocationViewModel. It doesn't look like you have this in your edit view right now, so you need to either a) add it to the viewbag from your controller and pass it via your RenderPartial call or b) change the model type in your edit view (you may need a wrapper that holds both the user and locationviewmodel information)
[Edit]
The source code would looks something like the following:
// ViewModel
namespace RolMVC3.Areas.Distributor.Models
{
public class EditPageViewModel
{
public LocationViewModel LocationViewModel {get;set;]
public USER User { get; set; }
}
}
// Edit View
#model RolMVC3.Areas.Distributor.Models.EditPageViewModel
#{
ViewBag.Title = "Edit User";
}
....
....
#Html.RenderPartial("_LocationEdit",Model.LocationViewModel);
....
....

Editor Template Not working in MVC3

I am trying out the Editor Template in MVC 3
My model class is
public class BookViewModel
{
public int Id { get; set; }
public string Name { get; set; }
[DataType(DataType.Text)]
public string Author { get; set; }
}
I have create a partial view for Editor template and put that in a EditorTemplates folder with name Text.cshtml. following is the partial view
#inherits System.Web.Mvc.WebViewPage<string>
<p> Write the name of author</p> #Html.TextBox(Model)
and I used #Html.EditorFor in the view page
<p> Name : #Html.EditorFor(model => model.Name)</p>
<p> Author</p> #Html.EditorFor(model => model.Author)
But when I run the program what I see is only an empty TextBox. I should see a TextBox filled with Author Name right?
What am I missing here?
Your editor template should be:
#model String
<p> Write the name of author</p> #Html.TextBox("name of the textbox", Model)
The first parameter of the #Html.TextBox() helper can be an empty string as well, but its not recommended

UIHint does not work with IList?

I have a property in my ViewMode:
[UIHint("FileUpload")]
public IList<string> Images { get; set; }
In view Create.cshtml
#html.ValidationSummary(true)
#html.EditorForModel()
In the folder Shared/EditorTemplates/FileUpload.cshtml
<h3>Test</h3>
But the field is not displayed. Simply, nothing happens!
I did the same test with another type of field and it worked:
[UIHint("FileUpload")]
public string Test { get; set; }
What could be wrong?
How do you solve this problem?
If I manually add the code below in my Create.cshtml view, it works!
#Html.EditorFor(m => m.Images)
I do not know what to do.
Yes, UIHint doesn't work with lists. You will need a loop inside the corresponding editor template (~/Views/Shared/EditorTemplates/FileUpload.cshtml). The UIHint template is passed the model which in this case is a IList<string>.
#model IList<string>
#foreach (var item in Model)
{
...
}

Resources