从asp.net mvc 3形式的强类型视图中收集数据

本文关键字:视图 强类型 数据 net asp mvc | 更新日期: 2023-09-27 18:12:24

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

这是我的设置:

我使用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]]的

从asp.net mvc 3形式的强类型视图中收集数据

您需要将视图中的Type从List<Auction>更改为Auction。因为你只是传递Auction和你的视图有模型类型作为List<Auction>它抛出这个错误。我强烈的猜测是,当您使用值列表测试它时,视图中的模型类型为通用列表,但稍后您将Action更改为返回Auction,但没有更改视图。

更改视图中的Model
@model List<Ebuy.Website.Models.Auction>

@model Ebuy.Website.Models.Auction