繁体   English   中英

C#visual studio asp.net将项目添加到列表属性

[英]C# visual studio asp.net adding an item to a list attribute

我目前正在为自行车店建模的项目。 在“订单”对象中,我有一个lis对象用于订单上的Bike项目。 如何将自行车添加到此列表? IE,我想在“创建”视图中显示可用自行车的列表,将一个或多个添加到订单中。

我的控制器:

        public ActionResult Create()
        {
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "OrderNumber,CustomerName,OrderDate,PickupDate,TotalCost,PaymentMethod")] Order order)
        {
            if (ModelState.IsValid)
            {
                db.Orders.Add(order);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(order);
        }

我的库存模型

public class Inventory
    {
        public int Id { get; set; }

        public string SerialNumber { get; set; }

        public virtual Store Store { get; set; }
        public int? StoreId { get; set; }

        public string Model { get; set; }

        public string Description { get; set; }

        public Decimal InventoryCost { get; set; }

        public Decimal RecSalePrice { get; set; }

        public Decimal SalePrice { get; set; }

        public string PaymentMethod { get; set; }

        public virtual BikeCategory Category { get; set; }
        public int? CategoryId { get; set; }







    }       

我的订单模型:

namespace BikeStore.Models
{

    public class Order
    {
        public Order()
        {
            OrderedItems = new List<Inventory>();
        }

        public string CustomerName { get; set; } //FROM CONTROLLER User.Identity.Name

        public virtual List<Inventory> OrderedItems { get; set; }


         [Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int OrderNumber { get; set; }

在订单的创建视图中:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Order</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.OrderDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.OrderDate, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.PickupDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PickupDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PickupDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TotalCost, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TotalCost, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TotalCost, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PaymentMethod, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PaymentMethod, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PaymentMethod, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

首先创建视图模型以表示要在视图中显示/编辑的内容(适当添加显示和验证属性)

public class InventoryVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}
public class OrderVM
{
  public string PaymentMethod { get; set; }
  public List<InventoryVM> Inventory { get; set; }
}

请注意, CustomerNameOrderDateTotal不适合(您不希望用户编辑它们-应该在保存订单之前立即在POST方法中设置它们)。 不知道PickupDate代表什么,但是如果它是实际日期,那也不适合(在收集订单时将单独设置)。 我也认为, PaymentMethod是枚举或集合PaymentType的和你在选择视图使用下拉列表。

那么GET方法将是

public ActionResult Create()
{
  // Get all available bikes, for example
  var inventory = db.Inventory;
  OrderVM model = new OrderVM
  {
    Inventory = inventory.Select(i => new
    {
      ID = i.ID,
      Name = i.Model // modify this to suit what you want to display in the view
    }).ToList()
  };
  return View(model);
}

并认为

@model yourAssembly.OrderVM
@using (Html.BeginForm())
{
  for(int i = 0; i < Model.Inventory.Count; i++)
  {
    @Html.HiddenFor(m => m.Inventory[i].ID)
    @Html.CheckBoxFor(m => m.Inventory[i].IsSelected)
    @Html.LabelFor(m => m.Inventory[i].IsSelected, Model.Inventory[i].Name)
  }
  @Html.TextBoxFor(m => m.PayentMethod)
  <input type="submit" value="Create" />
}

而POST方法将是

public ActionResult Create(OrderVM model)
{
  // Initialize a new Order and map properties from view model
  var order = new Order
  {
    CustomerName = User.Identity.Name,
    OrderDate = DateTime.Now,
    ....
    PaymentMethod = model.PaymentMethod
  }
  // Save the order so that you now have its `ID`
  IEnumerable<int> selectedItems = model.Inventory.Where(i => i.IsSelected).Select(i => i.ID);
  foreach(var item in selectedItems)
  {
    // You have not shown the model for this so just guessing
    var orderItem = new OrderItem{ OrderID = order.Id, InventoryId = item };
    db.OrderItems.Add(orderItem);
  }
  db.SaveChanges();
}

旁注:

  1. 如果您希望允许用户选择任何一项以上,则可以将bool IsSelected更改为int Quantity
  2. 如果要显示有关项目的其他信息,请说“ DescriptionCost ,则可以在InventoryVM视图模型中包括其他属性,并使用@Html.DisplayFor(m => m.Inventory[i].Description)显示它们。
  3. 如果要在视图中显示所有选定项目的总费用,则需要使用javascript / jquery
  4. 如果ModelState可能无效,则需要在返回视图之前重新填充InventoryVM的属性(仅ID回发的IDIsSelected属性),或者在视图中包括其他属性的隐藏输入

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM