【问题标题】:how to make View of create type with two model如何用两个模型制作创建类型的视图
【发布时间】:2016-11-04 02:35:29
【问题描述】:

我有一个与两个模型绑定的视图...所以我选择ViewModel 方法将两个模型与一个视图绑定...但是我在创建Create 类型的视图时遇到了问题...但是我我面临错误...FeedbackMix 在这里是 ViewModel...我必须传递查询对象以在布局中显示某些内容,同时我必须创建类型视图页面...
错误:强>

CS1061:“FeedbackMixModel”不包含“Message”的定义,并且找不到接受“FeedbackMixModel”类型的第一个参数的扩展方法“Message”(您是否缺少 using 指令或程序集引用?)

控制器

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>
    ....
}

视图模型

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; }
}

错误行

第 16 行:@Html.LabelFor(model => model.Message, htmlAttributes: new { @class= "control-label col-md-2" })

【问题讨论】:

  • 错误信息非常简单...在您的FeedbackMixModel 中您没有Message 属性或方法
  • 是的,我知道我粘贴了这段代码,这样你们就可以轻松理解了场景。

标签: c# asp.net-mvc


【解决方案1】:

您的FeedbackViewModel 上没有名为Message 的属性,而您的LabelFor() 助手正在期待它,因此它不知道如何绑定它:

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>
}

【讨论】:

  • 对于我使用 FOrEach 循环的内容,它只是创建类型 View。并且此视图使用的布局需要一个查询对象 ..所以我必须使用 ViewModel,因为这是 table1 的创建类型视图(包类),同时我必须传递另一个表的查询对象,比如 table2(通知类),以便布局通过部分视图显示 somthing..我希望你理解我的问题..实际上我不知道如何创建创建类型从视图模型查看...
猜你喜欢
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2011-08-02
  • 1970-01-01
相关资源
最近更新 更多