2013-10-08 22 views
1

我有以下看法:BeginForm與IEnumerable的

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

什麼是最好的修復方法?

回答

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

完美,非常感謝 –

0

做@model YIS2.Models.AddTestimonialViewModel

,扔前面的推薦進入ViewBag,所以你會有

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