Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C visual studio asp.net将项添加到列表属性_C#_Html_Asp.net Mvc_Visual Studio 2013 - Fatal编程技术网

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

C# C visual studio asp.net将项添加到列表属性,c#,html,asp.net-mvc,visual-studio-2013,C#,Html,Asp.net Mvc,Visual Studio 2013,我目前正在做一个项目来模拟一个自行车店。在我的“订单”对象中,我有一个用于订单上自行车项目的lis对象。如何将自行车添加到此列表中?例如,我想在“创建”视图中显示可用自行车的列表,并将其中一个或多个添加到订单中 我的控制器: public ActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToke

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

我的控制器:

        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; }
}
在我看来

@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()
{
  // 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);
}
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();
}
旁注:

如果您希望允许用户选择任意一个或多个选项 项目,您可以更改布尔值,选择显示整数数量 如果要显示有关项目的其他信息, 说明说明和成本您可以包括其他属性 在InventoryVM视图模型中,使用 @Html.DisplayForm=>m.Inventory[i]。说明 如果要显示中所有选定项目的总成本 视图,则需要使用javascript/jquery 如果ModelState可能无效,则需要重新填充 返回视图之前的InventoryVM属性,如图所示 只有ID和IsSelected属性回发或包含 视图中其他属性的隐藏输入
不要将实体框架的实体模型类用作视图模型。这两个概念是截然不同的,尽管它们的名字中都有model。您在这里到底看到了一个ViewModel吗?不清楚您的问题是什么。是否要在“订单”视图中显示可用自行车的列表,以便选择要包含在订单中的多个自行车中的一个?所有这些代码的相关性是什么?例如,你删除的方法与问题有什么关系?@StephenMuecke是的,没错。首先从你的问题中删除所有不相关的代码,我们可能倾向于看一看:谢谢!但是,I.m在IEnumerable selectedItems=order.Inventory.Wherei=>I.IsSelected时出现运行时错误;我一直在那里得到一个例外。你知道这是怎么回事吗?哎呀,在.Selecti=>i.ID位的左边,请看编辑,它是IEnumerable而不是IEnumerableAnd,它的模型是。Inventory不是order。Inventory似乎可以工作,但仍然得到ArgumentNullException,在同一位置。你知道会出什么问题吗?