1

我知道这可能看起来很容易找到答案,但我发现了很多关于如何从控制器发送数据并将其显示在视图中的文章,并且没有明确的方法来收集/使用控制器中提交的数据。

这是我的设置:

我使用 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.List1[Ebuy.Website.Models.Auction]'.]`

4

1 回答 1

1

您需要将视图中的 Type 从 更改List<Auction>Auction。因为您只传递了Auction并且您的视图具有模型类型,因为List<Auction>它会引发此错误。我的强烈猜测是,当您使用值列表对其进行测试时,您在视图中将模型类型作为通用列表,但您稍后将您的操作更改为返回拍卖但没有更改您的视图。

更改视图中的模型

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

@model Ebuy.Website.Models.Auction
于 2013-05-05T18:27:40.687 回答