ASP.NET MVC3 View模型不是null,但在发回Controller时缺少数据

时间:2012-03-01 14:28:50

标签: asp.net-mvc asp.net-mvc-3

以下是我的情况:

我有一个名为OrderFromCategory的控制器动作,它用数据填充视图模型(在这种情况下,视图模型只是另一个视图模型类型的项目列表)。这将传递给强类型视图,该视图显示项目列表并允许用户更改每个项目的数量。在Post上,我的post控制器操作会返回模型对象,但列表中没有对象。我错过了接线的东西吗?不知所措,任何帮助将不胜感激!非常感谢!

另外,我的验证是否正确连线?在我让模型数据持久化之前无法测试它!

以下是代码:

视图模型:

public class MenuItemsModel
{
    public MenuItemsOrderModel()
    {
        items = new List<MenuItemOrderModel>();
    }

    public List<MenuItemOrderModel> items { get; set; }
}

public class MenuItemOrderModel
{
    public int ItemID { get; set; }

    [Display(Name = "Name")]
    public string ItemName { get; set; }

    [Display(Name = "Description")]
    public string Description { get; set; }

    [Display(Name = "Price")]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [Display(Name = "Quantity")]
    public int Quantity { get; set; }

    public string Qualifier { get; set; }
    public int Minimum { get; set; }
}

控制器:

    public ActionResult OrderFromCategory(string id)
    {
        ViewData["category"] = id;
        Models.MenuItemsModel model = new Models.MenuItemsModel();

        foreach (Models.MenuItem item in Models.MenuItemRepository.GetMenuItemsForCategory(id))
        {
            model.items.Add(new Models.MenuItemOrderModel()
            {
                ItemID = item.ItemID,
                Description = item.Description,
                ItemName = item.Name,
                Price = item.Price,
                Qualifier = item.PriceQualifier,
                Minimum = item.MinimumQuantity,
                Quantity = ((namespace.Models.Order)Session["order"]).GetItemQuantity(item.ItemID)
            });
        }

        return View(model);
    }

    [HttpPost]
    public ActionResult OrderFromCategory(string id, Models.MenuItemsModel model)
    {
        //check for user inputs in all items
        foreach (string inputKey in Request.Form.AllKeys)
        {
            Models.MenuItem item = Models.MenuItemService.GetMenuItem(int.Parse(inputKey));
            int minimum = item.MinimumQuantity;
            int quantity = string.IsNullOrEmpty(Request.Form[inputKey]) ? 0 : int.Parse(Request.Form[inputKey]);

            if(quantity != 0 && quantity < minimum)
            {
                ModelState.AddModelError(string.Format("Quantity", item.ItemID), string.Format("Minimum of {0} required for order", minimum));
            }

            if (!ModelState.IsValid)
            {
                return View(model);
            }

            Models.OrderService.UpdateItemInOrder((Models.Order)Session["order"], item.ItemID, quantity);
        }

        return RedirectToAction("PlaceOrder");
    }

查看:

@model namespace.Models.MenuItemsModel
@{
    ViewBag.Title = "Order from  " + ViewData["category"];
}

<h2>Order from @ViewData["category"] </h2>

<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, "Order was unsuccessful. Please correct the errors and try again.")    
    <div>
        <fieldset>

        @foreach (namespace.Models.MenuItemOrderModel item in Model.items)
        {
            <div class="item_group">

              <div class = "item_name">
                @item.ItemName
              </div>
              <div class = "item_description">
                @item.Description
              </div>
              <div class = "item_price">
                $@item.Price /@item.Qualifier  (@item.Minimum miminum)
              </div> 
              <div class = "item_quantity">
                <div class="editor-label">
                    Quantity
                </div>
                <div class="editor-field">
                    @Html.TextBox(item.ItemID.ToString(), item.Quantity.ToString(), new { @class = "quantity_textbox", @type = "number"})
                    @Html.ValidationMessage("Quantity", "*")
                </div>
              </div>

            </div>
        }

        <p>
            <input type="submit" value="Continue" />
        </p>

        </fieldset>
   </div>
}

1 个答案:

答案 0 :(得分:6)

您的表单中似乎没有相应的输入字段用于视图模型的字段。您的数量文本框的命名也是错误的。尝试使用以下内容替换视图中的foreach循环:

@for (int i = 0; i < Model.items.Count; i++)
{
    @Html.HiddenFor(x => x.items[i].ItemID)
    @Html.HiddenFor(x => x.items[i].ItemName)
    @Html.HiddenFor(x => x.items[i].Description)
    @Html.HiddenFor(x => x.items[i].Price)
    @Html.HiddenFor(x => x.items[i].Qualifier)
    @Html.HiddenFor(x => x.items[i].Minimum)

    <div class="item_group">
        <div class = "item_name">
            @Model.items[i].ItemName
        </div>
        <div class = "item_description">
            @Model.items[i].Description
        </div>
        <div class = "item_price">
            $@Model.items[i].Price /@Model.items[i].Qualifier  (@Model.items[i].Minimum miminum)
        </div> 
        <div class = "item_quantity">
        <div class="editor-label">
            Quantity
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(x => x.items[i].Quantity, new { @class = "quantity_textbox", @type = "number" })
            @Html.ValidationMessageFor(x => x.items[i].Quantity, "*")
        </div>
        </div>
    </div>
}