简体   繁体   中英

ASP.NET Core: How to add a second model to my View

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 :)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM