我知道这可能看起来很容易找到答案,但我发现了很多关于如何从控制器发送数据并将其显示在视图中的文章,并且没有明确的方法来收集/使用控制器中提交的数据。
这是我的设置:
我使用 Visual Studio 为 mvc 项目创建的默认结构,因此在HomeController
我将 Ìndex 更改为:
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]'.]`