POST后空引用异常

时间:2016-08-08 13:07:11

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5

我有一个表单,它从模型中获取一些值。然后,在POST中,处理输入的数据用户并将用户重定向到另一页面。但是每次我发布表单时,我都会得到null-reference exeption。我在哪里犯错?

提出这个问题的其他问题都没有解决我的问题,这就是为什么我再次询问我的具体代码。

exeptions在foreach循环 - Model.Cart,Model.ShippingOptionsm等。

d

控制器:

@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")
}

1 个答案:

答案 0 :(得分:0)

在页面顶部添加模型声明

@model CheckoutViewModel