具有IEnumerable的BeginForm [英] BeginForm with IEnumerable

查看:63
本文介绍了具有IEnumerable的BeginForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下观点:

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

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?

推荐答案

如果您需要使用 IEnumerable< Testimonial> 发回 见证代码>无法正常工作.我建议您创建一个组合视图模型,并通过它,即

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; }
}

然后您认为

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

这篇关于具有IEnumerable的BeginForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆