我有一个 View 与两个模型绑定(bind)...所以我选择 ViewModel
方法将两个模型与一个 View 绑定(bind)...但是我在创建 Create View 时遇到了问题
type ...但我遇到错误...FeedbackMix 是 ViewModel 在这里...我必须传递查询对象以在布局中显示某些内容,同时我必须创建 Create type view page ...
错误:
CS1061: 'FeedbackMixModel' does not contain a definition for 'Message' and no extension method 'Message' accepting a first argument of type 'FeedbackMixModel' could be found (are you missing a using directive or an assembly reference?)
Controller
public ActionResult Create()
{
var msg= db.Messages.ToList();
var feed = db.Feedbacks.ToList();
FeedbackMixModel vm = new FeedbackMixModel();
vm.allfeedbacks = feed;
//this is also create type view
return View(vm);
}
查看
@model WebApplication5.Models.FeedbackMixModel
....
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
....
@Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
</div>
....
}
View 模型
public class FeedbackMixModel
{
public List<UserManager> allUserManagers { get; set; }
public List<Feedback> allfeedbacks { get; set; }
public List<Package> allpackages { get; set; }
public List<Messages> allmessages { get; set; }
}
错误行
Line 16: @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
最佳答案
您的 FeedbackViewModel
上没有名为 Message
的属性,您的 LabelFor()
助手需要它,所以它没有知道如何绑定(bind)它:
public class FeedbackMixModel
{
public List<UserManager> allUserManagers { get; set; }
public List<Feedback> allfeedbacks { get; set; }
public List<Package> allpackages { get; set; }
public List<Messages> allmessages { get; set; }
// No property named Message here
}
如果你想要这样的东西,你需要添加属性并在将它传递给模型之前填充它。
您确定您不是要循环遍历您的 allMessages
属性并从这些单独的元素访问它吗?
<h4>Messages</h4>
<hr />
@foreach(var message in Model.allMessages)
{
<div class="form-group">
@Html.LabelFor(message => message.Message, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(message => message.Message, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(message=> message.Message, "", new { @class = "text-danger" })
</div>
</div>
}
关于c# - 如何使用两个模型制作创建类型的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38149514/