Reputation: 43
I'm reading data from my view. And I need to pass data to controller via model. But the problem is that I need to pass data to model in model.
I've tried this one
@foreach (var item in Model.Items)
{
@Html.TextBoxFor(item.ItemCount, null, new { @class="input_quantity-
value", value = "2.5", data_type="area", data_width="2.5"})
}
but this is incorrect
Here's my code for view
@model TechnoTent.Models.ViewModel.OrderVM
@using (Html.BeginForm("EditOrder", "AdminOrder", FormMethod.Post, new {
@class = "product-edit", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@foreach (var item in Model.Items)
{
@Html.TextBoxFor(item.ItemCount, null, new {
@class="input_quantity-value", value = "2.5", data_type="area", data_width="2.5"})
}
}
Here code for controller
[HttpPost]
public ActionResult EditOrder(OrderVM order)
{
AdminOrders.EditOrder(order);
return View();
}
and here's a part of code for my model
public class OrderVM
{
public List<OrderItemsVM> Items { get; set; }
}
and here's a part of code for my OrderItemsVM model
public class OrderItemsVM
{
public string ItemCount { get; set; }
}
I need to read ItemCount from a view to my OrderItemsVm. Is it possible somehow? or better to have a List in a base model and to read it there?
Upvotes: 0
Views: 1586
Reputation: 1883
Please change below code in views
cshtml page
@model TechnoTent.Models.ViewModel.OrderVM
@using (Html.BeginForm("EditOrder", "AdminOrder", FormMethod.Post, new {
@class = "product-edit", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
for(int i=0; i < Model.Items.Count;i++)
{
@Html.TextBox("Items["+i+"].ItemCount", "2.5", new {
@class="input_quantity-value", value = "2.5", data_type="area", data_width="2.5"})
}
}
cshtml page if you want set model values in controller like you are editing the data
@model TechnoTent.Models.ViewModel.OrderVM
@using (Html.BeginForm("EditOrder", "AdminOrder", FormMethod.Post, new {
@class = "product-edit", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
for(int i=0; i < Model.Items.Count;i++)
{
@Html.TextBox("Items["+i+"].ItemCount",Model.Items[i].ItemCount , new {
@class="input_quantity-value", value = "2.5", data_type="area", data_width="2.5"})
}
}
Upvotes: 1
Reputation: 304
Your controller and view models look fine to me. This is how I would do the views. First add a folder "EditorTemplates" inside the Views folder. Then create OrderItemsVM.cshtml view inside that folder.
/EditorTemplates/OrderItemsVM.cshtml:
@model TechnoTent.Models.ViewModel.OrderItemsVM
<div>
@Html.TextBoxFor(model => model.ItemCount, new { @class = "..." })
</div>
In your form page, get rid of @foreach(...){...} block and replace it with @Html.EditorFor(model => model.Items)
YourFormPage.cshtml:
@model TechnoTent.Models.ViewModel.OrderVM
@using (Html.BeginForm(...))
{
@Html.AntiForgeryToken()
@Html.EditorFor(model => model.Items)
...
}
Upvotes: 0