Reputation: 1880
my index view has a model that looks like this:
@model IEnumerable<WebSurvey.Data.Models.Question>
and is used by this:
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Question1)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReplyOptions)
</td>
<td>
@Html.DisplayFor(modelItem => item.Group)
</td>
<tr>
}
</tbody>
but i also need a model that looks like this:
@model WebSurvey.Data.Models.Question
so that I can use the properties of "Questions" in "asp-for" to create a new Question, because it does not work with the current model.
My question: Is there a way to create another model in my view?
Hope you can help me out :)
Upvotes: 2
Views: 142
Reputation: 5944
You should consider always creating a model with a name that corresponds with your view instead of focusing first on what data you might be going to display.
If your view is called Questions, you should create a model called QuestionsViewModel.
public class QuestionsViewModel { }
After that, you can think about what data you want to add, so if you have a list of questions add it to the class as a property.
public class QuestionsViewModel
{
public IEnumerable<Question> Questions { get; set; }
}
/// In your view
@foreach (var question in Model.Questions)
{
}
Later you decide you also need a User
.
public class QuestionsViewModel
{
public IEnumerable<Question> Questions { get; set; }
public User User { get; set; }
}
/// In your view
<span>@Model.User.Username</span>
@foreach (var question in Model.Questions)
{
}
The point is, you can now add as many properties as you like.
Upvotes: 1
Reputation: 2909
You shouldn't try to add a 2nd model. You want to wrap the 2 models in a parent model.
public class BlueprintFor {
public IEnumerable<Question> Questions {get;set;}
public Question Question {get;set;}
}
If you further struggle with using the wrap model to create a form, separate the wrap model by passing one of the child models in to a partial view which contains the form.
Upvotes: 1