我知道這可能看起來很容易找到答案問題,但我發現了很多關於如何從控制器發送數據並將其顯示在視圖中的文章,沒有明確的方式來收集/使用控制器中提交的數據。從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]」]`
我什麼都沒有做刻意。我的意思是 - 我希望我的視圖接受拍賣列表,因爲正如你在我的邏輯中看到的,我遍歷這個列表來填充我的表格。所以我需要這個List。所以我需要將@model留給列表,任何建議如何以這種方式發回它? – Leron 2013-05-05 18:36:25
所以你希望你的視圖採取名單以及拍賣權?你在第二個HTTPPost索引中做什麼? –
PSL
2013-05-05 18:37:53
您在控制器中的回答後,我將我的索引方法更改爲:[HttpPost] public ActionResult Index(List model) var test = model; return查看(model); }' –
Leron
2013-05-05 18:41:57