2013-05-05 42 views
1

我知道這可能看起來很容易找到答案問題,但我發現了很多關於如何從控制器發送數據並將其顯示在視圖中的文章,沒有明確的方式來收集/使用控制器中提交的數據。從asp.net mvc 3格式的強類型視圖中收集數據

這是我的設置:

我使用Visual Studio的創建MVC項目的默認結構,以便在HomeController我改變了指數:

public class HomeController : Controller 
     { 
      public ActionResult Index() 
      { 
       ViewBag.Message = "Create table"; 
       var model = new List<Auction>(); 
       model.Add(new Auction 
       { 
        Title = "First Title", 
        Description = "First Description" 
       }); 
       model.Add(new Auction 
       { 
        Title = "Second Title", 
        Description = "Second Description" 
       }); 
       model.Add(new Auction 
       { 
        Title = "Third Title", 
        Description = "Third Description" 
       }); 
       model.Add(new Auction 
       { 
        Title = "Fourht Title", 
        Description = "Fourth Description" 
       }); 

       return View(model); 
      } 

I just hard coded some data so I can play around with it. 

then this is my Index view : 

@model List<Ebuy.Website.Models.Auction> 

@{ 
    ViewBag.Title = "Home Page"; 
} 


@using (Html.BeginForm()) 
{ 
    <table border="1" > 
     @for (var i = 0; i < Model.Count(); i++) 
     { 
      <tr> 
       <td> 
        @Html.HiddenFor(x => x[i].Id) 
        @Html.DisplayFor(x => x[i].Title) 
       </td> 
       <td> 
        @Html.EditorFor(x => x[i].Description) 
       </td> 
      </tr> 
     } 
    </table> 

    <button type="submit">Save</button> 
} 

而且我在HomeController想了想這將是足以讓從該視圖的信息:

[HttpPost]

public ActionResult Index(Auction model) 
{ 
    var test = model; 
    return View(model); 
} 

好吧,看起來並不那麼容易。我得到這個錯誤:

[InvalidOperationException: The model item passed into the dictionary is of type 'Ebuy.Website.Models.Auction', but this dictionary requires a model item of type 'System.Collections.Generic.List 1 Ebuy.Website.Models.Auction]」]`

回答

1

您需要在您的視圖更改類型從List<Auction>Auction。因爲你傳遞的只是Auction而你的視圖的模型類型爲List<Auction>,它會引發這個錯誤。我強烈的猜測是,當您使用值列表測試它時,您將視圖中的模型類型視爲泛型列表,但稍後您將Action更改爲返回Auction,但並未更改視圖。

@model List<Ebuy.Website.Models.Auction> 

更改模型的視圖中的

@model Ebuy.Website.Models.Auction 
+0

我什麼都沒有做刻意。我的意思是 - 我希望我的視圖接受拍賣列表,因爲正如你在我的邏輯中看到的,我遍歷這個列表來填充我的表格。所以我需要這個List。所以我需要將@model留給列表,任何建議如何以這種方式發回它? – Leron 2013-05-05 18:36:25

+0

所以你希望你的視圖採取名單以及拍賣權?你在第二個HTTPPost索引中做什麼? – PSL 2013-05-05 18:37:53

+1

您在控制器中的回答後,我將我的索引方法更改爲:[HttpPost] public ActionResult Index(List model) var test = model; return查看(model); }' – Leron 2013-05-05 18:41:57