我要做的是有一页创建新的房子,并且还可以放置所有现有房屋。 主视图的代码是:
@modelData.Models.SGHouse
@{
ViewBag.Title = "";
}
<h2>Create</h2>
@using (Ajax.BeginForm(new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "HouseList"
}))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SGHouse</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@*<div class="form-group">
@Html.LabelFor(model => model._id, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model._id, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model._id, "", new { @class = "text-danger" })
</div>
</div>*@
<div class="form-group">
@Html.LabelFor(model => model.House, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.House, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.House, "", 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>
}
@Html.Partial("_Houses",Model)
我的部分视图列出所有房屋的代码是:
@model IEnumerable<Data.Models.SGHouse>
<div id="HouseList">
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.House)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.House)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item._id }) |
@Html.ActionLink("Details", "Details", new { id = item._id }) |
@Html.ActionLink("Delete", "Delete", new { id = item._id })
</td>
</tr>
}
</table>
</div>
如果我这样做,我不确定从我的控制器返回什么视图:
public ActionResult Create()
{
return View();
}
我从部分视图中得到关于模型的错误是null。 如果我使用:
public ActionResult Create()
{
return View(new SGHouse());
}
然后我收到错误
传递到字典中的模型项是'Data.Models.SGHouse'类型,但是这个字典需要一个类型为'System.Collections.Generic.IEnumerable`1 [Data.Models.SGHouse]'的模型项。 / p>
如何解决此问题的任何帮助。
由于
答案 0 :(得分:2)
在类中创建一个新属性
public class SGHouse
{
public List<SGHouse> ListSGHouse { get; set; }
}
在Constroller中
public ActionResult Create()
{
SGHouse model = new SGHouse();
List<SGHouse> LstSGHouse = new List<SGHouse>();
LstSGHouse = //Just add list of SGHouse to this property
model.ListSGHouse = LstSGHouse; //Assign above to this
return View(model);
}
在视图中调用就像这样
@Html.RenderPartial("_Houses", Model.ListSGHouse);
确保在部分视图中检查模型不为空
@if (Model != null)
{
}