ViewModel不在POST上更新

时间:2012-04-24 01:00:47

标签: asp.net-mvc-3 entity-framework viewmodel

我有一个控制器和视图,允许用户“签出”购物车的内容。

当我的CheckoutController将Order模型返回到Checkout视图时,一切正常。但是,我现在还希望在Checkout视图上显示购物车的内容,因此修改了Controller和View以使用包含Order和CartItems的viewmodel。

我创建了一个CheckoutViewModel并修改了GET:和POST:ActionResults以使用此视图模型。

问题是在POST期间没有正确填充CheckOutViewModel:

我在这行'checkoutViewModel.Order.Username = User.Identity.Name;'中收到'对象引用未设置为对象的实例'错误在POST:ActionResult但我不确定究竟是什么没有实现。

如果需要,我可以发布使用Oreder模型而不是CheckoutViewModel的原始工作编码。

我确信我有一些简单的结构或语法问题,我只是无法分辨它是什么,因为我仍然试图了解在MVC中做事的最佳方式。

GET:ActionResult

    //GET: /Checkout/AddressAndPayment
    public ActionResult AddressAndPayment()
    {
        //To pre-populate the form, create a new Order object and get the ShoppingCart, populate the ViewModel and pass it to the view
        var order = new Order();
        order.Username = User.Identity.Name;
        MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
        storeDB.SaveChanges();

        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Set up our ViewModel
        var viewModel = new CheckoutViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal(),
            Order = order
        };

        // Return the view
        return View(viewModel);
    }  

POST:ActionResult

        //POST: /Checkout/AddressAndPayment
    [HttpPost]
    public ActionResult AddressAndPayment(FormCollection values)
    {
        var checkoutViewModel = new CheckoutViewModel();
        TryValidateModel(checkoutViewModel);

        try
        {
            checkoutViewModel.Order.Username = User.Identity.Name;
            checkoutViewModel.Order.OrderDate = DateTime.Now;
            //Save Order
            storeDB.Orders.Add(checkoutViewModel.Order);
            storeDB.SaveChanges();
            //Process the order
            var cart = ShoppingCart.GetCart(this.HttpContext);
            cart.CreateOrder(checkoutViewModel.Order);
            storeDB.SaveChanges();
            //Send 'Order Confirmation' email
            ViewData["order"] = checkoutViewModel.Order;
            UserMailer.OrderConfirmation(checkoutViewModel.Order).SendAsync();

            return RedirectToAction("Complete", new { id = checkoutViewModel.Order.OrderID });
        }
        catch
        {
            //Invalid - redisplay with errors
            return View(checkoutViewModel);
        }
   }  

查看

@model OrderUp.ViewModels.CheckoutViewModel
@{
    ViewBag.Title = "AddressAndPayment";
}
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) { 
@Html.ValidationSummary(true)
<h2>Pick Up Details</h2>
<fieldset>
    <legend>When are you gonna be hungry?</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Order.Phone)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Order.Phone)
        @Html.ValidationMessageFor(model => model.Order.Phone)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Order.PickUpDateTime)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Order.PickUpDateTime)
        @Html.ValidationMessageFor(model => model.Order.PickUpDateTime)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Order.Notes)
    </div>
    <div class="editor-multiline-field">
        @Html.EditorFor(model => model.Order.Notes)
        @Html.ValidationMessageFor(model => model.Order.Notes)
    </div>
</fieldset>
<input type="submit" value="Submit Order" />
}
<div style="height:30px;"></div>
<h3>
    <em>Review</em> your cart:
 </h3>
<table>
<tr>
    <th>
        Menu Item
    </th>

    <th>
        Price (each)
    </th>
    <th>
        Notes
    </th>
    <th>
        Quantity
    </th>
    <th></th>
</tr>
@foreach (var item in Model.CartItems)
{
    <tr id="row-@item.RecordID">
        <td>
            @Html.ActionLink(item.MenuItem.Name, "Details", "Store", new { id = item.MenuItemID }, null)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.MenuItem.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Notes )
        </td>
        <td id="item-count-@item.RecordID">
            @item.Count
        </td>
        <td>
        </td>
    </tr>
}
<tr>
    <td >
        Total
    </td>
    <td  id="cart-total">
        @String.Format("${0:F2}", Model.CartTotal)
    </td>
    <td>
    </td>
    <td>
    </td>
    <td>
    </td>
</tr>
</table>

1 个答案:

答案 0 :(得分:2)

你应该使用CheckoutViewModel作为HttpPost方法的输入参数,然后尝试调试,看看你是否仍然没有在表单发布后填充该模型。

[HttpPost]
    public ActionResult AddressAndPayment(CheckOutViewModel checkoutViewModel)
    {
        TryValidateModel(checkoutViewModel);

        try
        {
            checkoutViewModel.Order.Username = User.Identity.Name;
            checkoutViewModel.Order.OrderDate = DateTime.Now;
            //Save Order
            storeDB.Orders.Add(checkoutViewModel.Order);
            storeDB.SaveChanges();
            //Process the order
            var cart = ShoppingCart.GetCart(this.HttpContext);
            cart.CreateOrder(checkoutViewModel.Order);
            storeDB.SaveChanges();
            //Send 'Order Confirmation' email
            ViewData["order"] = checkoutViewModel.Order;
            UserMailer.OrderConfirmation(checkoutViewModel.Order).SendAsync();

            return RedirectToAction("Complete", new { id = checkoutViewModel.Order.OrderID });
        }
        catch
        {
            //Invalid - redisplay with errors
            return View(checkoutViewModel);
        }
   }