BeginForm与IEnumerable的(BeginForm with IEnumerable)

2019-10-18 18:30发布

我有以下看法:

@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" />
}

我需要的型号是IEnumerable的,所以我可以通过内容重复先前显示保存的见证。 问题是我上语句米=> Model.x因为模型是IEnumerable的一个错误。

什么是修复,请最好的方法是什么?

Answer 1:

如果您需要回发一个 Testimonial使用IEnumerable<Testimonial>是行不通的。 我建议你创建一个组合视图模型和传递,而不是即

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

然后在您的视图

@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" />
}


Answer 2:

做@model YIS2.Models.AddTestimonialViewModel

扔前面的推荐进入ViewBag,所以你必须

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


文章来源: BeginForm with IEnumerable