Passing @ Html.DisplayFor () - values from view to controller
I have the following classes:
public class ProductViewModel
{
public IEnumerable<Product> Products { get; set; }
}
public class Product
{
public int ArticeNr { get; set; }
public string Name { get; set; }
}
And this look
@model ProductsViewModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table class="table">
@foreach (var item in Model.Products) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ArticleNr)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
<input type="submit" value="submit" name="submitButton" />
}
How do I pass all my values from Model.Products to the controller? I want all my values in the foreach loop to be sent to the controller
My controller takes ProductViewModel as a parameter. But the values after the message in model.Products
are zero.
public ActionResult Index(ProductsViewModel model) //here, model.Products is always null after post
{
//LOGIC
}
source to share
Here, I'll walk you through how to publish a collection in ASP.Net MVC 3 using a sample application. The main idea behind publishing (passing HTML field values from the view to the controller) is to map the name field of the rendered HTML control to the receive parameters in the controller action method.
ASP.Net MVC - publishing collection
source to share
As far as I can see, you are not changing your values in the foreach loop - so you are sending the same values as your view received to display. In this case, keep your model class, but change your index and home controller like this
View:
@model Models.ProductViewModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table class="table">
@foreach (var item in Model.Products)
{
<tr>
<td>
@item.ArticleNr
</td>
<td>
@item.Name
</td>
</tr>
}
</table>
<input type="submit" value="submit" />
}
controller:
[HttpGet]
public ActionResult Index()
{
return View(new ProductViewModel()); // this model contains products you want to display
}
[HttpPost]
public ActionResult Index(ProductViewModel model)
{
// do smth with your model here
return View();
}
I suspect that your problems were the result of your actions without the [HttpGet] and [HttpPost] attributes
source to share