C#的Visual Studio asp.net将项目添加到列表属性 [英] C# visual studio asp.net adding an item to a list attribute

查看:94
本文介绍了C#的Visual Studio asp.net将项目添加到列表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作的一个项目到bikestore建模。在我的秩序的对象,我对订单上的自行车项目凡属对象。我将如何增加自行车这个名单?即我想在创建视图中显示availiable自行车的列表,一个添加一个或更多的人的顺序

我的控制器:

 公众的ActionResult的Create()
        {
            返回查看();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        公众的ActionResult创建([绑定(包括=订单编号,客户名称,订购日期,PickupDate,TOTALCOST,PAYMENTMETHOD)]订购订购)
        {
            如果(ModelState.IsValid)
            {
                db.Orders.Add(订单);
                db.SaveChanges();
                返回RedirectToAction(「指数」);
            }            返回查看(订单);
        }

我的库存模型

 公共类库存
    {
        公众诠释标识{搞定;组; }        公共字符串的SerialNumber {搞定;组; }        公共虚拟店中店{搞定;组; }
        公众诠释? STOREID {搞定;组; }        公共字符串模式{搞定;组; }        公共字符串描述{搞定;组; }        公共小数InventoryCost {搞定;组; }        公共小数RecSalePrice {搞定;组; }        公共小数SalePrice {搞定;组; }        公共字符串PAYMENTMETHOD {搞定;组; }        公共虚拟BikeCategory类别{搞定;组; }
        公众诠释? {类​​别ID获取;组; }    }

我的订单模式:

 命名空间BikeStore.Models
{    公共类订单
    {
        公共秩序()
        {
            OrderedItems =新的List<库存和GT;();
        }        公共字符串客户名称{搞定;组; } //来自控制器User.Identity.Name        公共虚拟目录<库存和GT; OrderedItems {搞定;组; }
         [关键词,DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)
        公众诠释ORDERNUMBER {搞定;组; }

在订单的创建视图:

  @using(Html.BeginForm())
{
    @ Html.AntiForgeryToken()    < D​​IV CLASS =形横>
        < H4>订单和LT; / H4>
        <小时/>
        @ Html.ValidationSummary(真,新{@class =TEXT-危险})
        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.CustomerName,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.CustomerName,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.CustomerName,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.OrderDate,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.OrderDate,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.OrderDate,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>
        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.PickupDate,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.PickupDate,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.PickupDate,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.TotalCost,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.TotalCost,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.TotalCost,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.PaymentMethod,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.PaymentMethod,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.PaymentMethod,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            < D​​IV CLASS =COL-MD-偏移2 COL-MD-10>
                <输入类型=提交值=创建类=BTN BTN-默认的/>
            < / DIV>
        < / DIV>
    < / DIV>
}< D​​IV>
    @ Html.ActionLink(返回目录,索引)
< / DIV>


解决方案

通过创建视图模型重新present要在视图中显示/编辑(添加显示器和适当的验证属性)什么时开始。

 公共类InventoryVM
{
  公众诠释ID {搞定;组; }
  公共字符串名称{;组; }
  公共BOOL IsSelected {搞定;组; }
}
公共类OrderVM
{
  公共字符串PAYMENTMETHOD {搞定;组; }
  公开名单< InventoryVM>库存{搞定;组; }
}

注意客户名称订购日期是不恰当的(你不希望用户编辑这些 - 他们应该在POST方法立即保存订单之前进行设置)。不知道是什么 PickupDate 重新presents但如果它的实际日期那么这是不恰当的是(这将是单独收集的订单时设置)。我也建议 PAYMENTMETHOD PaymentType 的一个枚举或集合以及您,并在使用一个DropDownList查看选项。

那么GET方法是

 公众的ActionResult的Create()
{
  //获取所有可用的自行车,例如
  VAR库存= db.Inventory;
  OrderVM模式=新OrderVM
  {
    库存= inventory.Select(I =>新建
    {
      ID = i.ID,
      名称= i.Model //修改此,以满足要在视图中显示的是什么
    })。了ToList()
  };
  返回查看(模型);
}

和视图

  @model yourAssembly.OrderVM
@using(Html.BeginForm())
{
  的for(int i = 0; I< Model.Inventory.Count;我++)
  {
    @ Html.HiddenFor(M = GT; m.Inventory [I] .ID)
    @ Html.CheckBoxFor(M = GT; m.Inventory [I] .IsSelected)
    @ Html.LabelFor(M = GT; m.Inventory [I] .IsSelected,Model.Inventory [I] .Name点)
  }
  @ Html.TextBoxFor(M = GT; m.PayentMethod)
  <输入类型=提交值=创建/>
}

和POST方法是

 公众的ActionResult创建(OrderVM模型)
{
  //初始化从视图模型的新秩序和地图属性
  VAR为了=新订单
  {
    客户名称= User.Identity.Name,
    订购日期= DateTime.Now,
    ....
    PAYMENTMETHOD = model.PaymentMethod
  }
  //保存秩序,使你现在有它的`ID`
  IEnumerable的< INT> selectedItems = model.Inventory.Where(I => i.IsSelected)。选择(I => i.ID);
  的foreach(在selectedItems VAR项)
  {
    //您还没有显示此所以只是猜测模型
    VAR OrderItem的新= {OrderItem的订单id = order.Id,InventoryId =项目};
    db.OrderItems.Add(OrderItem的);
  }
  db.SaveChanges();
}

旁注:


  1. 如果您希望能够让用户选择更多的那一个
    项目时,你可以改变布尔IsSelected INT数量

  2. 如果您要显示有关项目的其他信息,
    说明成本您可以包括附加的属性
    InventoryVM 视图模型,并显示它们
    @ Html.DisplayFor(M = GT; m.Inventory [I]。说明)

  3. 如果您想在所有选定的项目显示总成本
    视图,您将需要使用JavaScript / jQuery的

  4. 如果的ModelState 可能是无效的,则需要重新填充
    你以前 InventoryVM 的属性返回视图(如图所示
    只有 ID IsSelected 属性回来后),或包括
    在视图中隐藏的输入其他属性

I am currently working on a project to model a bikestore. In my 'Order' object, I have a lis object for the Bike items on the order. How would I add bikes to this list? I.E I want to display a list of availiable bikes in the Create view, an add one or more of them to the order.

My Controller:

        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);
        }

My Inventory model

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; }







    }       

My Order model:

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; }

In the create view for orders:

@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>

解决方案

Start by creating view models to represent what you want to display/edit in the view (add display and validation attributes as appropriate)

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; }
}

Note that CustomerName, OrderDate and Total are not appropriate (you don't want a user editing these - they should be set in the POST method immediately before saving the order). Not sure what PickupDate represents but if its the actual date then that's not appropriate either (it would be set separately when the order is collected). I would also suggest that PaymentMethod be an enum or collection of PaymentType's and that you and use a dropdownlist in the view for selection.

Then the GET method would be

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);
}

And in the view

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

And the POST method would be

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();
}

Side notes:

  1. If you want to be able to allow users to select more that one of any item, the you could change bool IsSelected to say int Quantity
  2. If you you want to display additional information about the items, say Description and Cost you can include additional properties in the InventoryVM view model and display them with @Html.DisplayFor(m => m.Inventory[i].Description)
  3. If you want to display a total cost for all selected items in the view, you will need to use javascript/jquery
  4. If ModelState could be invalid, you will need to repopulate the properties of InventoryVM before you return the view (as shown only the ID and IsSelected properties post back) or include hidden inputs for the other properties in the view

这篇关于C#的Visual Studio asp.net将项目添加到列表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆