POST Data Model Empty If Other Row Is Selected – MVC C#

From the view you posted, you have a form per each row! Hence whenever you post back to the server, you’re only sending one order ID.

If you only need an order ID in order to re-order, you should create your Reorder method to only take an order ID:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Reorder(int orderId)
{
    return View();
}

If you want the user to be able to select multiple orders and re-order them, then you would probably change the view model a little bit:

// I am totally guessing
public class OrderHistoryViewModel
{
    public IEnumerable<OrderViewModel> Orders { get; set; }
}

public class OrderViewModel
{
    public int OrderId { get; set; }

    public bool SelectedToReorder { get; set; }
}

Then you initialize the order list on your [HttpGet] method:

public class OrderHistoryController : Controller
{
    public ActionResult Index()
    {
        var vm = new OrderHistoryViewModel
        {
            Orders = // Get the orders from your persistence layer
        };

        return View(vm);
    }
}

Then in the index.cshtml view, instead of putting multiple forms, you would just need one:

@model OrderHistoryViewModel

<h3>Order History</h3>
@using (Html.BeginForm("reorder", "orderhistory", new { area = "" }, FormMethod.Post, null)
{
    @Html.AntiForgeryToken()

    for (int i = 0; i < Model.Orders.Count(); i++)
    {
        @Html.HiddenFor(x => x.Orders[i].Id)
        @Html.CheckboxFor(x => x.Orders[i].SelectedToReorder)
    }

    <button type="submit">Re-order</button>
}

Finally, in your [HttpPost] method, you can filter those orders the user selects and process your logic:

public class OrderHistoryController : Controller
{
    public ActionResult Index()
    {
        var vm = new OrderHistoryViewModel
        {
            Orders = // Get the orders from your persistence layer
        };

        return View(vm);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Reorder(OrderHistoryViewModel model)
    {
        if (ModelState.IsValid)
        {
            var selectedOrderIds = model.Orders
                .Where(x => x.SelectedToReorder == true)
                .ToArray();

            // Keep going

            return RedirectToAction ...;
        }

        return View...;
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top