传递给字典的模型项的类型为'System.Collections.Generic.List`1',但是字典需要类型为``.Locations'的模型项

时间:2018-07-25 09:04:22

标签: c# asp.net-mvc asp.net-mvc-4 model-view-controller

嗨,我正在尝试从Controller返回创建视图,并且收到上述异常。 我搜索了它,但找不到解决方案。我什至尝试从MVC模板生成新的控制器,但仍然无法正常工作。

下面是我的代码

  public ActionResult Create()
        {
            return View();
        }

        // POST: LocationsView/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,UserId,LastModifiedDate")] Locations locations)
        {
            if (ModelState.IsValid)
            {
                db.Location.Add(locations);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(locations);
        }

下面是我的视图

@model ConstructApi.Models.Locations


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Locations</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        @*<div class="form-group">
            @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control"  , @Value = ViewBag.UserId} })
                @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
            </div>
        </div>*@


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这是完整的异常消息

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ConstructApi.Models.Locations]', but this dictionary requires a model item of type 'ConstructApi.Models.Locations'.

任何帮助将不胜感激。预先感谢。

0 个答案:

没有答案