繁体   English   中英

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

[英]Collect data from a strongly-typed view in asp.net mvc 3 form

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

这是我的设置:

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

您需要将视图中的类型从List<Auction>更改为Auction 因为您仅传递Auction并且视图的模型类型为List<Auction>所以会引发此错误。 我的强烈猜测是,当您使用值列表进行测试时,视图中的模型类型为通用列表,但后来选择了操作以返回拍卖,但未更改视图。

在视图中更改模型

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

@model Ebuy.Website.Models.Auction

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM