Reputation: 15
I am new in MVC programming with razor and I need your advice on what is wrong with my code.
I have a Model
public class OrderDetails : OrderList
{
public string CompanyId { get; set; }
public List<OrderItems> OrdItems { get; set; }
}
public class OrderItems
{
public int Id { get; set; }
public string StopAddressName { get; set; }
}
I have a controller that populate data.
public ActionResult Edit()
{
OrderDetails ordDtl = new OrderDetails();
ordDtl.CompanyId = "1";
ordDtl.OrdItems = new List<OrderItems>();
for (int i = 1; i < 4; i++)
{
OrderItems tmp = new OrderItems();
tmp.Id = i;
tmp.StopAddressName = "Street " + i;
ordDtl.OrdItems.Add(tmp);
}
return View("EditOrder", ordDtl);
}
When I send it to view it shows all data. Here is my view.
@model OrderDetails
@using (Html.BeginForm("Edit", "Orderlayouts", FormMethod.Post))
{
<fieldset><legend>OrderDetail</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CompanyId)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.CompanyId)
</div>
<table>
<tr>
<td>id</td>
<td>Address</td>
</tr>
@foreach (var itm in Model.OrdItems)
{
<tr>
<td>@itm.Id</td>
<td>@itm.StopAddressName</td>
</tr>
}
</table>
<p>
<input type="submit" value="Edit" />
</p>
</fieldset>
}
When I click the submit button I have in controller CompanyID, but OrdItems values become null. Can you point out what is going wrong with my code. Here is my controller.
[HttpPost]
public ActionResult Edit(OrderDetails Orderdt)
{
return View("EditOrder", Orderdt);
}
Any suggestions will be greatly appreciated.
Upvotes: 1
Views: 3099
Reputation: 239450
I'm assuming OrderDetails
is an entity (tied to a database table via Entity Framework). For all entities with navigation properties of a list-type, you must use an ICollection
. Additionally, all navigation properties, whether a single foreign key or a list, must be virtual. EF does not actually return your class, but rather a proxy of your class with the navigation properties overridden to return the proper objects. If it's not virtual, EF can't make the override and you get a null value instead. So your model should look like:
public class OrderDetails : OrderList
{
public string CompanyId { get; set; }
public virtual ICollection<OrderItems> OrdItems { get; set; }
}
Upvotes: 0
Reputation: 7375
Model binding is honestly the bane of my MVC work.
Here, however, you're going to see a form
style post that only contains companyID - no other form fields for it to be using to bind are in your view.
Upvotes: 0
Reputation: 2221
I would try doing Something like this.
@for (int i = 0; i < Model.OrdItems.Count; i++)
{
@Html.DisplayFor(model => model.OrdItems[i].Id)@Html.HiddenFor(model => model.OrdItems[i].Id)
@Html.DisplayFor(model => model.OrdItems[i].StopAddressName)@Html.HiddenFor(model => model.OrdItems[i].StopAddressName)
}
Upvotes: 2