Hi @Andrew Harkins ,
In Asp.net MVC application, the foreach
statement and the @Html.DisplayFor
is used to list the page model. If you are using the F12 developer Elements tools to check the rendered html resource, you can see that, it directly show the property value, without using an html element with the name
attribute. Like this:
So, when you click the submit button and submit this form, you can't get the page model data at the controller.
To solve this issue, you can add hidden field with the @Html.DisplayFor
method. Like this:
<td>
@Html.DisplayFor(item => p.ItemLocation)
<input type="hidden" asp-for="@p.ItemLocation" name="[@i].ItemLocation">
</td>
Or, you can try to use for
statement and the Html.TextBoxFor
or Html.RadioButtonFor
to display the property value.
Code like this:
The controller:
public IActionResult ShoppingIndex()
{
var initdata = new List<ShoppingCar>()
{
new ShoppingCar(){ ProductID=101, Name="A", Item="Item 1", Price= 2.1, Quantity=5 },
new ShoppingCar(){ ProductID=102, Name="B", Item="Item 2", Price= 2.2, Quantity=6 },
new ShoppingCar(){ ProductID=103, Name="C", Item="Item 3", Price= 23, Quantity=7 },
new ShoppingCar(){ ProductID=104, Name="D", Item="Item 4", Price= 2.4, Quantity=8 },
new ShoppingCar(){ ProductID=105, Name="E", Item="Item 5", Price= 2.5, Quantity=9 },
};
return View(initdata);
}
[HttpPost]
public IActionResult ShoppingIndex(List<ShoppingCar> cars, string radio)
{
return View();
}
and ShoppingCar model:
public class ShoppingCar
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Item { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
//for the checkbox.
public bool IsSelected { get; set; }
}
Besides, about the radio button, using your code, since the radio button will use the same name, you can only select one row, and you can get the select row value via the name attribute.
But, if you want to select multiple rows, you can refer the above sample: add a IsSelected property in the page model, then use the Html.RadioButtonFor
to display the radio button, and on its change event set the value to true or false. Then, you can according to the IsSelected property to get the select rows.
The result like this:
Note: when using the above code, it will use the submit button to submit the form and the page model, if you want to only submit the selected row data to the controller, you use the radio button click event, then use JQuery to get the selected row data and then use JQuery Ajax to call the controller with the selected row data.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion