使用IEnumerable的BeginForm

时间:2013-10-08 19:33:58

标签: asp.net-mvc razor

我有以下观点:

@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 =&gt; Model.x因为Model是IEnumerable。

最好的解决方法是什么?

2 个答案:

答案 0 :(得分: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" />
}

答案 1 :(得分:0)

@model YIS2.Models.AddTestimonialViewModel

将以前的推荐信投入ViewBag,这样你就有了

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