I am facing a problem for passing data to a controller.
I have a class that contains a list. I pass an instance of my object in my controller to retrieve my view. Which is actually a form. And when I submit my form, the object becomes empty, then there's that he depart at least two entries in the list. I have used the same method name to retrieve my data via Form.Method.
This is my code :
Model
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; }
}
View
@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>
Partial View
@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>
Controller
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");
}
}
}