1

我有以下看法:

@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 的,这样我就可以遍历内容以显示以前保存的推荐信。问题是我在语句 m => Model.x 上遇到错误,因为 Model 是 IEnumerable。

请问最好的解决方法是什么?

4

2 回答 2

6

如果您需要回发一个单一 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" />
}
于 2013-10-08T19:39:29.560 回答
0

做@model YIS2.Models.AddTestimonialViewModel

并将之前的推荐信扔到 ViewBag 中,这样你就有了

@foreach (var item in ViewBag.PreviousTestimonials)
{
    <blockquote>
        <p>@item.Content</p>
        <p>@item.AuthorName</p>
    </blockquote>
}
于 2013-10-08T19:43:28.963 回答