2015-04-21 70 views
1

類型的模型項目我需要在編輯頁面中傳遞兩個模型(因爲我想構建一個MVC 4項目,視圖模型),但是當我嘗試插入在編輯頁面視圖模型,我有如下錯誤:傳入字典的模型項目類型爲'System.Data.Entity.DynamicProxies.People',但該字典需要

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.People_E82A8FE6694DFF4D5ED1869045FE3E0A1855CC3CA65B873F5F1556DABC2DC9F4', but this dictionary requires a model item of type 'MVC_ViewModel.Models.ViewModel'.

編輯頁面(視圖):

@model MVC_ViewModel.Models.ViewModel 

@{ 
    ViewBag.Title = "Edit"; 
} 

<h2>Edit</h2> 

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>People</legend> 

     @Html.HiddenFor(model => model.People.PeopleID) 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.People.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.People.Name) 
      @Html.ValidationMessageFor(model => model.People.Name) 
     </div> 

     <p> 
      <input type="submit" value="Save" /> 
     </p> 
    </fieldset> 
} 

指數頁面(查看):

@model IEnumerable<MVC_ViewModel.People> 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<p> 
    @Html.ActionLink("Create New", "Create") 
</p> 
<table> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.Name) 
     </th> 
     <th></th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Name) 
     </td> 
     <td> 
      @Html.ActionLink("Edit", "Edit", new { id=item.PeopleID }) | 
      @Html.ActionLink("Details", "Details", new { id=item.PeopleID }) | 
      @Html.ActionLink("Delete", "Delete", new { id=item.PeopleID }) 
     </td> 
    </tr> 
} 

</table> 

ViewModel類(模型):

namespace MVC_ViewModel.Models 
{ 
    public class ViewModel 
    { 
     public Car Car { get; set; } 
     public List<Car> Cars { get; set; } 
     public People People { get; set; } 
     public List<People> Peoples { get; set; } 
     public Detail Detail { get; set; } 
     public List<Detail> Details { get; set; } 
    } 
} 

CRUD(控制器):

public ActionResult Index() 
{ 
    return View(db.People.ToList()); 
} 

... 

public ActionResult Edit(int id = 0) 
{ 
    People people = db.People.Find(id); 
    if (people == null) 
    { 
     return HttpNotFound(); 
    } 
    return View(people); 
} 

// 
// POST: /CRUDViewModel/Edit/5 

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit(People people) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Entry(people).State = EntityState.Modified; 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    return View(people); 
} 

我需要理解錯誤,如果有人能幫助我。謝謝!

回答

3

你已經在你的ASP.NET 編輯頁,你的模式類型爲ViewModel規定:

@model MVC_ViewModel.Models.ViewModel 

然後你傳遞一個People對象。在您提供的代碼中沒有任何地方使用ViewModel

如果你把這裏改爲:

@model MVC_ViewModel.People 

,並切換到model.*model.People.*引用,那麼錯誤應該消失。

但是,我建議你應該返回一個PeopleViewModel和映射各種屬性。閱讀一些博客,教程和如何最好地構建這些內容的例子可能會很有用。

相關問題