我收到上面的错误消息。我已经查看了其他问题,似乎无法查明错误。这是我为控制器提供的代码。这是我得到的错误:
System.InvalidOperationException:具有键'RecieverID'的ViewData项的类型为'System.String',但必须是'IEnumerable< SelectListItem>'的类型
public ActionResult Create()
{
ViewBag.RecieverID = new SelectList(db.AspNetUsers, "Id", "Email");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RecieverID,TEXT")] Message message)
{
if (ModelState.IsValid)
{
var mes = new Message
{
SenderID = User.Identity.GetUserId(),
DATETIMEMADE = DateTime.Now,
TEXT = message.TEXT
};
db.Messages.Add(mes);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ReceiverID = new SelectList(db.AspNetUsers, "Id", "Email", message.RecieverID);
return View(message);
}
之后是我创建消息的观点:
@model MUE.Models.Message
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Message</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.RecieverID, "RecieverID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("RecieverID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.RecieverID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.TEXT, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.TEXT, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.TEXT, "", 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>
不确定问题的来源,但我们将非常感谢任何帮助。
答案 0 :(得分:0)
首先,不要成为纳粹语法,但它应该是“接收者”而不是“接收者”。
其次,model.RecieverID表示单个字段,而不是集合。
“新的SelectList(...”是集合。
答案 1 :(得分:0)
您可以为页面创建一个ViewModel,例如:
public class MyViewModel
{
public SelectList ReceiverList
public MUE.Models.Message ReceivedMessage
}
在控制器中分配您的值,然后执行以下操作:
@Html.DropDownListFor(model => model.ReceivedMessage.ReceiverID, Model.ReceiverList, new { @class = "form-control" })