gpt4 book ai didi

asp.net-mvc - BeginForm 与 IEnumerable

转载 作者:行者123 更新时间:2023-12-02 17:42:15 25 4
gpt4 key购买 nike

我有以下看法:

@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。

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

最佳答案

如果您需要回发单个 Testimonial使用 IEnumerable<Testimonial>不会工作。我建议您创建一个组合 View 模型并传递它,即

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

关于asp.net-mvc - BeginForm 与 IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19256693/

25 4 0