I have a form, which gets some values from model. Then, in POST the data user entered are handled and user is redirected to another page. However everytime I post the form, I get null-reference exeption. Where do I make a mistake?
None of the other questions asking about this didn´t solve my problem, that´s why I am asking again with my specific code.
The exeptions are at foreach loops - Model.Cart, Model.ShippingOptionsm etc.
@model CheckoutViewModel
@{
ViewBag.Title = "Checkout";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Checkout</h2>
<table class="table">
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Quantity</td>
<td>Price</td>
<td>Total price</td>
</tr>
</thead>
@foreach (CartItem i in Model.Cart)
{
<tr>
<td>@Html.Action("ProductPosition", "Cart", new { item = i })</td>
<td>@i.Name</td>
<td>@i.Quantity</td>
<td>@i.Price €</td>
<td>@i.Total €</td>
</tr>
}
</table>
<h3>Total: @Html.Action("TotalPrice", "Cart") €</h3>
@using (Html.BeginForm("Checkout", "Cart"))
{
@Html.AntiForgeryToken()
<h2>Address</h2>
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Address)
@Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Address)
</div>
<div class="form-group">
@Html.LabelFor(m => m.City)
@Html.TextBoxFor(m => m.City, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.City)
</div>
<div class="form-group">
@Html.LabelFor(m => m.PostNumber)
@Html.TextBoxFor(m => m.PostNumber, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.PostNumber)
</div>
<div class="form-group">
@Html.LabelFor(m => m.State)
@Html.TextBoxFor(m => m.State, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.State)
</div>
<h2>Shipping</h2>
foreach (var i in Model.ShippingOptions)
{
<div class="radio">
@Html.RadioButtonFor(m => m.ShippingOption, i.Id) @i.Name - @i.Price €
</div>
}
@Html.ValidationMessageFor(m => m.ShippingOption);
<h2>Payment</h2>
foreach (var i in Model.PaymentOptions)
{
<div class="radio">
@Html.RadioButtonFor(m => m.PaymentOption, i.Id) @i.Name
</div>
}
@Html.ValidationMessageFor(m => m.PaymentOption);
<button type="submit" class="btn btn-primary">Continue</button>
}
@section scripts
{
@Scripts.Render("~/bundles/jqueryval")
}
Controller:
public ActionResult Checkout()
{
if (Session["cart"] == null)
return RedirectToAction("Index");
var checkout = new CheckoutViewModel()
{
Cart = (List<CartItem>)Session["cart"],
PaymentOptions = _context.PaymentOptions.ToList(),
ShippingOptions = _context.ShippingOptions.ToList()
};
return View(checkout);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Checkout(CheckoutViewModel m)
{
if (!ModelState.IsValid)
return View();
//TODO: handle data
return RedirectToAction("OrderSuccess");
}