我一直試圖讓兩個模型出現在使用ViewModels的單個視圖中,但是失敗了。無法將兩個模型合併到一個ViewModel中
我現在有3個字段的簡單視圖(評論,姓名,部門)以及與之匹配的模型。我有一個控制器返回一個空視圖,當你提交表單時,空模型被填充並傳回給控制器。我現在想要將部門字段變成一個下拉列表,並推導出(也許不正確?),我應該創建另一個模型,其中包含靜態值,然後通過控制器將ViewModel傳遞給視圖,但是當我嘗試執行此操作時,它失敗:
查看:
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="fieldset">
<fieldset>
<legend>CommentDb</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Comment)
</div>
<div>
@Html.TextAreaFor(model => model.Comment, new {style = "width: 900px; height:200px;", autocomplete = "off" })
@Html.ValidationMessageFor(model => model.Comment)
</div>
<div class="editor-label">
@Html.Label("Your Name")
@*@Html.LabelFor(model => model.CommentByName)*@
@Html.TextBoxFor(model => model.CommentByName, new { autocomplete = "off", placeholder = "Optional" })
@Html.ValidationMessageFor(model => model.CommentByName)
</div>
<div class="editor-label">
@Html.Label("Your Department", new { @class = "display-label" })
@*@Html.LabelFor(model => model.Department)*@
@Html.TextBoxFor(model => model.Department, new { autocomplete = "off", placeholder = "Optional" })
@Html.ValidationMessageFor(model => model.Department)
</div>
</fieldset>
<br />
<br />
</div>
<div>
<input type="submit" value="Create" id="submit"/>
</div>
}
部下拉模式:
namespace SuggestionBox.Models
{
public class DropDownModel
{
public String Departments { get; set; }
public String SetDropDownList()
{
Departments = "Engineering";
return Departments;
}
}
}
數據基本型號:
namespace SuggestionBox.Models
{
public class CommentModel
{
[Key]
public int CommentiD { get; set; }
public string CommentByName { get; set; }
public string Department { get; set; }
[Required]
public string Comment { get; set; }
public DateTime InsertDate { get; set; }
}
}
namespace SuggestionBox.Models
{
public class CommentDbContext : DbContext
{
public CommentDbContext() : base()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<CommentDbContext, SuggestionBox.Migrations.Configuration>());
}
public DbSet<CommentModel> Comments { get; set; }
}
}
我試圖視圖模型:
namespace SuggestionBox.ViewModels
{
public class SuggestionBoxViewModel
{
public CommentModel Comments { get; set; }
public DropDownModel Departments { get; set; }
public SuggestionBoxViewModel()
{
Departments = new DropDownModel();
Departments.SetDropDownList();
Comments = new CommentModel();
}
}
}
控制器:
public ViewResult Index()
{
SuggestionBoxViewModel vm = new SuggestionBoxViewModel();
return View(vm);
}
在return View(vm);
,在IDE說:Arguement型「SuggestionBox.ViewModels .SuggestionBoxViewModel'不是可分配給模型類型'SuggestionBox.Models.CommentModel'
任何想法我在這裏做錯了嗎?
乾杯。
你好像在視圖中指定CommentModel'的'模型類型,而不是SuggestionBoxViewModel'的'。 – 2014-10-07 20:27:02
謝謝傑森。就是這樣! DUH! :-) – 2014-10-07 21:01:09