BeginForm with IEnumerable

2019-07-29 18:55发布

问题:

I have the following view:

@model IEnumerable<YIS2.Models.Testimonial>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div id="Testimonials">
    <h2>Our Testimonials</h2>
    @foreach (var item in Model)
    {
        <blockquote>
            <p>@item.Content</p>
            <p>@item.AuthorName</p>
        </blockquote>
    }
</div>


<div id="SubmitTestimonial">
<h2>Submit Testimonial</h2>


@using (Html.BeginForm("NewTestimonial", "Testimonial", FormMethod.Post))
{
    @Html.EditorFor(m => Model.AuthorName)
    @Html.EditorFor(m => Model.AuthorEmail)
    @Html.EditorFor(m => Model.Content)
    <input type="submit" id="submitTestimonial" />
}

I need the model to be IEnumerable so I can iterate through the content to show previously saved testimonials. Problem is I get an error on the statements m => Model.x because Model is IEnumerable.

What's the best way to fix please?

回答1:

If you need to post back a single Testimonial using IEnumerable<Testimonial> isn't going to work. I suggest you create a combined view model and pass that instead i.e.

public class AddTestimonialViewModel
{
    public IEnumerable<Testimonial> PreviousTestimonials { get; set; }
    public Testimonial NewTestimonial { get; set; }
}

Then in your view

@model YIS2.Models.AddTestimonialViewModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div id="Testimonials">
    <h2>Our Testimonials</h2>
    @foreach (var item in Model.PreviousTestimonials)
    {
        <blockquote>
            <p>@item.Content</p>
            <p>@item.AuthorName</p>
        </blockquote>
    }
</div>


<div id="SubmitTestimonial">
<h2>Submit Testimonial</h2>


@using (Html.BeginForm("NewTestimonial", "Testimonial", FormMethod.Post))
{
    @Html.EditorFor(m => m.NewTestimonial.AuthorName)
    @Html.EditorFor(m => m.NewTestimonial.AuthorEmail)
    @Html.EditorFor(m => m.NewTestimonial.Content)
    <input type="submit" id="submitTestimonial" />
}


回答2:

Do @model YIS2.Models.AddTestimonialViewModel

And throw the previous testimonials into the ViewBag, so you'd have

@foreach (var item in ViewBag.PreviousTestimonials)
{
    <blockquote>
        <p>@item.Content</p>
        <p>@item.AuthorName</p>
    </blockquote>
}