【发布时间】:2014-12-04 14:56:07
【问题描述】:
我在将数据传递给控制器时遇到了问题。
我有一个包含列表的类。我在我的控制器中传递我的对象的一个实例来检索我的视图。这实际上是一种形式。当我提交表单时,对象变为空,然后他离开了列表中的至少两个条目。我使用相同的方法名称通过 Form.Method 检索我的数据。
这是我的代码:
型号
public class XMLRecord
{
public string TypeDoc { get; set; }
public string Type { get; set; }
public string Contenu { get; set; }
public string DocName { get; set; }
public IEnumerable<XMLRecord> Records { get; set; }
}
查看
@model ManageXML.Models.XMLRecord
<body>
@using (Html.BeginForm("HandleForm", "XMLRecord", FormMethod.Post, new { @class = "form-horizontal", @role = "form", @id = "FormCreateXML" }))
{
<fieldset>
<legend> XML Editor</legend>
@if (Model.Records == null)
{
<p>None</p>
}
else
{
<ul id="XmlEditor" style="list-style-type: none">
@foreach (var record in Model.Records)
{
Html.RenderPartial("XmlEditor", record);
}
</ul>
<button type="button" class="btn btn-default" id="addAnother">Add another</button>
}
</fieldset>
<p>
<button type="submit" class="btn btn-default">Save</button>
<button type="button" class="btn btn-default"><a href="/">Cancel</a></button>
</p>
}
</body>
局部视图
@model ManageXML.Models.XMLRecord
<li style="padding-bottom:15px" >
@using (Html.BeginCollectionItem("XmlRecords")) {
<img src="@Url.Content("~/Content/images/draggable.jpg")" height="20"width="20" style="cursor: move" alt=""/>
@Html.LabelFor(model => model.Type)
@Html.EditorFor(model => model.Type)
@Html.LabelFor(model => model.Contenu)
@Html.EditorFor(model => model.Contenu)
<a href="#" onclick="$(this).parent().remove();">Delete</a>
}
</li>
控制器
public class XMLRecordController : Controller
{
[HttpGet]
public ActionResult HandleForm()
{
var file = new XMLRecord()
{
Records = new List<XMLRecord>(){
new XMLRecord(){Type="Title", Contenu="Head of Service"},
new XMLRecord(){Type="Item", Contenu="Dr. A.Libois"}
}
};
return View(file);
}
[HttpPost]
public ActionResult HandleForm(XMLRecord file)
{
if (file == null)
{
return HttpNotFound();
}
else
{
return Content("It's OK");
}
}
}
【问题讨论】:
-
只有 for helper 中的项目(显示除外)将绑定到模型并在发布时传回控制器
-
您可能想要使用 EditorTemplate 而不是
Html.RenderPartial("XmlEditor", record);。 (@Html.EditorFor(x => record)) -
感谢您的帮助。不明白马特的评论。你能解释一下吗?
-
XmlEditor部分是什么样的?
标签: asp.net xml asp.net-mvc-4