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

时间:2013-05-05 18:23:42

标签: c# asp.net-mvc-3 razor

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

这是我的设置:

我使用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]”。]`

1 个答案:

答案 0 :(得分:1)

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

在视图中更改模型

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

@model Ebuy.Website.Models.Auction