I am fairly new to MVC5. So far I seem to have searched my way through into solving my issues, however, I've come across a problem that I cannot figure out the solution.
I am creating two Views, one for creating a new Article Post, and one for Editing current Article Posts.
My article model is as follows:
public class Article
{
private int? _id;
[BsonRequired]
[DataType(DataType.Text)]
[BsonElement("_id")]
public int? Id
{
get { return _id ?? 999999; }
set { _id = value; }
}
...
[HiddenInput]
[BsonElement("related")]
public List<Related> Related { get; set; }
[HiddenInput]
[BsonElement("comments")]
public List<Comment> Comments { get; set; }
[HiddenInput]
[BsonElement("auto_publish")]
public AutoPublish AutoPublish { get; set; }
}
}
My issue is with Lists of Model Items (like List<Comment>
, List<Related>
) and the custom Model property.
In my Post and Edit views, i have set @Html.HiddenFor attributes for all of my model properties, but I am having a particularly hard time to NOT lose values for my custom model properties (like AutoPublish) and my list of model properties.
Correct me if I'm wrong, but for List of string items, I have used the following logic:
for (var i = 0; i < Model.Categories.Count; i++)
{
@Html.HiddenFor(model => Model.Categories[i])
}
For the other custom Lists, I tried creating a DisplayTemplate, with the following code:
@model List<CMS.Models.Comment>
@foreach (var item in Model)
{
@Html.HiddenFor(x => item.Date)
@Html.HiddenFor(x => item.Email)
@Html.HiddenFor(x => item.Enabled)
@Html.HiddenFor(x => item.Ip)
@Html.HiddenFor(x => item.Username)
@Html.HiddenFor(x => item.PostId)
@Html.HiddenFor(x => item.Text)
}
However, when I try to use @Html.DisplayForModel("Comments", Model.Comments) within my View, I get a model type mismatch.
Could someone please point me in the right direction? Thank you so much for your time.
DisplayForModel
is specific to the view's model. You can't pass any random object into it. You're probably looking for DisplayFor(m => m.Comments)
, but bear in mind that when you pass an enumerable to DisplayFor
, it actually renders the display template for each item in the collection. In other words, you need to remove the foreach
in your partial view, and change the model declaration to a single Comment
instead of a List<Comment>
.
EDIT
Actually, since you're rendering HiddenInput
s this should be an editor template, and you should be using EditorFor
. DisplayFor
is only for, well, display. Everything else I said still applies with EditorFor
.