将JQuery添加到asp.net mvc视图

时间:2022-11-30 17:37:50

I am currently working on a project to model a bikestore. I want to use Jquery in the Order.create view to cause only inventory items that belong to the store selected in the DropDownList to appear in the selectlist in the same view. How would I go about this?

我目前正在开展一个模拟自行车商店的项目。我想在Order.create视图中使用Jquery,使只有属于DropDownList中所选商店的库存项目出现在同一视图的选择列表中。我怎么会这样呢?

Order.Create:

<div class="form-group">
            @for(int i = 0; i < Model.Inventory.Count; i++)
            {
                <div class="col-md-10">
                    @Html.HiddenFor(m => m.Inventory[i].Name)
                    @Html.HiddenFor(m => m.Inventory[i].Id)
                    @Html.HiddenFor(m => m.Inventory[i].Price)
                    @Html.CheckBoxFor(m => m.Inventory[i].IsSelected)
                    @Html.LabelFor(m => m.Inventory[i].IsSelected, Model.Inventory[i].Name)
                    @Html.DisplayFor(m => m.Inventory[i].Price)
                </div>
            }
            <div class="col-md-10">
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name)
                @Html.LabelFor(m => m.PaymentMethod)
                @Html.TextBoxFor(m => m.PaymentMethod)
                @Html.LabelFor(model => model.StoreId, "StoreId", htmlAttributes: new { @class = "control-label col-md-2" })
                @Html.DropDownList("StoreId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.StoreId, "", new { @class = "text-danger" })
            </div>
            </div>

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

Store Model:

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

        public string Name { get; set; }

        public string City { get; set; }

        public string State { get; set; }

        public int Zip { get; set; }

        public string Address { get; set; }

        public string Phone { get; set; }

        public string Hours { get; set; }

        public virtual List<Employee> Employees { get; set; }

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

        public Store() 
        {
            Name = "";
            Employees=new List<Employee>();
            StoreInventory = new List<Inventory>();
        }

Order Model:

 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; }
        //public virtual List<Account> Accounts { get; set; }
        public DateTime? OrderDate { get; set; }

        public DateTime? PickupDate { get; set; }

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

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

        public Decimal TotalCost { get; set; }

        public string PaymentMethod { get; set; }

OrderVM Model:

public class OrderVM


     {
            public virtual Store Store { get; set; }
            public int? StoreId { get; set; }
            public string Name { get; set; }
            public string PaymentMethod { get; set; }
            public List<InventoryVM> Inventory { get; set; }
        }

InventoryVM Model:

public class InventoryVM
    {
        public decimal Price { get; set; }
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsSelected { get; set; }
        public virtual Store Store { get; set; }
        public int? StoreId { get; set; }
    }

OrderedItemModel:

OrderController:

public class OrdersController : Controller
    {
        private BikeStoreContext db = new BikeStoreContext();

        // GET: Orders

        public ActionResult Index()
        {
            return View(db.Orders.ToList());
        }

        // GET: Orders/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            return View(order);
        }

        // GET: Orders/Create
        public ActionResult Create()
        {
            var inventory = db.StoreInventory;
            OrderVM model = new OrderVM
            {
                Inventory = inventory.Select(i => new InventoryVM { Id = i.Id, Name = i.Model, Price=i.RecSalePrice}).ToList()

            };
            ViewBag.StoreId= new SelectList(db.Stores, "Id", "Name");

            return View(model);
        }

        // POST: Orders/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "PaymentMethod, Inventory")]OrderVM model)
        {
            var Order = new Order
            {

                CustomerName = model.Name,
                OrderDate = DateTime.Now,
                PaymentMethod = model.PaymentMethod,
                TotalCost=0,
                PickupDate=DateTime.Now.AddDays(7),
                StoreOrderedFrom=db.Stores.Find(model.StoreId),
                StoreId=model.StoreId


            };

            IEnumerable<int> selectedItems = model.Inventory.Where(i => i.IsSelected).Select(i => i.Id);
            foreach(var item in selectedItems)
            {
                var orderItem = new OrderedItem { OrderId = Order.OrderNumber, InventoryId = item };
                db.OrderedItems.Add(orderItem);
                Order.TotalCost = Order.TotalCost + model.Inventory.Find(i => i.Id == item).Price;
                db.StoreInventory.Remove(db.StoreInventory.Find(item));
            }
            db.Orders.Add(Order);
            db.SaveChanges();
            model.Inventory.RemoveAll(i => i.IsSelected);
            db.SaveChanges();
            ViewBag.StoreId = new SelectList(db.Stores, "Id", "Name", model.StoreId);
            return View(model);

        }

        // GET: Orders/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            return View(order);
        }

        // POST: Orders/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "OrderNumber,CustomerName,OrderDate,PickupDate,TotalCost,PaymentMethod")] Order order)
        {
            if (ModelState.IsValid)
            {
                db.Entry(order).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(order);
        }

        // GET: Orders/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            return View(order);
        }

        // POST: Orders/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Order order = db.Orders.Find(id);
            db.Orders.Remove(order);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }

1 个解决方案

#1


0  

The question is a bit unclear (you should delete the irrelevant code), however I will try my best to answer it. I hope I understand what you are looking for.

问题有点不清楚(你应该删除不相关的代码),但我会尽力回答它。我希望我明白你在寻找什么。

First off, there are a few javascript libraries that does what you are looking for (ajax filtering data tables) eg. DataTables and jTable

首先,有一些javascript库可以满足您的需求(ajax过滤数据表),例如。 DataTables和jTable

However, its easy to implement your own simple data table.

但是,它易于实现您自己的简单数据表。

So first let me start with what I understand about your question:

首先让我从我对你的问题的理解开始:

  • An Order can have multiple inventory items assigned to it.
  • 订单可以分配多个库存物料。

  • An Order has only a single store assigned to it.
  • 订单只分配了一个商店。

  • In your view you need a drop down to select the Store.
  • 在您的视图中,您需要下拉菜单才能选择商店。

  • When selecting a Store, that should populate an Inventory list which is pretty much a data table. You are using a @for loop to load it and display it in your view, but after selecting a Store from the drop down list it does not update the inventory list asynchronously.
  • 选择商店时,应该填充一个几乎是数据表的库存清单。您正在使用@for循环加载它并在视图中显示它,但从下拉列表中选择一个存储后,它不会异步更新清单列表。

Hence we are going to use the $.ajax route to update the Inventory list after selecting the store.

因此,我们将在选择商店后使用$ .ajax路线更新库存清单。

Here's what you can do:

First replace the Inventory @for loop list in your view with a div element and an id attribute.

首先使用div元素和id属性替换视图中的Inventory @for循环列表。

<div id="inventory-list">  </div>

Then add an event on StoreId element when changed.

然后在更改时在StoreId元素上添加事件。

$("#StoreId").change(function() {

    var selectedStoreId = $('#StoreId').val();

    $.ajax({
        url: '@Url.Action("GetInventoryForStore", "Orders")',
        type: "GET",
        dataType: "json",
        data: { storeId: selectedStoreId },
        beforeSend: function() {
            //clear the div element
            $("#inventory-list").empty();

            //add gif spinner here to show its loading
        },
        success: function (data) {
            if (data != null)
            {
                var items = '<table><tr><th>Name</th><th>Id</th></tr>';
                $.each(data, function (i, item) {
                    //I only added name and Id, but you can add the rest as well
                    items += "<tr><td>" + item.Name + "</td><td>" + item.Id + "</td></tr>";
                });
                items += "</table>";

                //add items to inventory div.
                $("#inventory-list").html(items);
            }
            else
            {
                //show the user that a problem occurred loading the data
                //update inventory-list with an error message
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
});

Then you can define a method in your OrdersController:

然后,您可以在OrdersController中定义一个方法:

[HttpGet]
public JsonResult GetInventoryForStore(int storeId)
{
    var store = db.Store.Find(storeId);

    if (store == null)
        return Json(null, JsonRequestBehavior.AllowGet);

    return Json(store.StoreInventory.ToList(), JsonRequestBehavior.AllowGet);
}

That should about do it. I hope this helps!

应该这样做。我希望这有帮助!

I have not tested the code, so if you see any mistakes, please edit the post.

我没有测试过代码,所以如果你发现任何错误,请编辑帖子。

#1


0  

The question is a bit unclear (you should delete the irrelevant code), however I will try my best to answer it. I hope I understand what you are looking for.

问题有点不清楚(你应该删除不相关的代码),但我会尽力回答它。我希望我明白你在寻找什么。

First off, there are a few javascript libraries that does what you are looking for (ajax filtering data tables) eg. DataTables and jTable

首先,有一些javascript库可以满足您的需求(ajax过滤数据表),例如。 DataTables和jTable

However, its easy to implement your own simple data table.

但是,它易于实现您自己的简单数据表。

So first let me start with what I understand about your question:

首先让我从我对你的问题的理解开始:

  • An Order can have multiple inventory items assigned to it.
  • 订单可以分配多个库存物料。

  • An Order has only a single store assigned to it.
  • 订单只分配了一个商店。

  • In your view you need a drop down to select the Store.
  • 在您的视图中,您需要下拉菜单才能选择商店。

  • When selecting a Store, that should populate an Inventory list which is pretty much a data table. You are using a @for loop to load it and display it in your view, but after selecting a Store from the drop down list it does not update the inventory list asynchronously.
  • 选择商店时,应该填充一个几乎是数据表的库存清单。您正在使用@for循环加载它并在视图中显示它,但从下拉列表中选择一个存储后,它不会异步更新清单列表。

Hence we are going to use the $.ajax route to update the Inventory list after selecting the store.

因此,我们将在选择商店后使用$ .ajax路线更新库存清单。

Here's what you can do:

First replace the Inventory @for loop list in your view with a div element and an id attribute.

首先使用div元素和id属性替换视图中的Inventory @for循环列表。

<div id="inventory-list">  </div>

Then add an event on StoreId element when changed.

然后在更改时在StoreId元素上添加事件。

$("#StoreId").change(function() {

    var selectedStoreId = $('#StoreId').val();

    $.ajax({
        url: '@Url.Action("GetInventoryForStore", "Orders")',
        type: "GET",
        dataType: "json",
        data: { storeId: selectedStoreId },
        beforeSend: function() {
            //clear the div element
            $("#inventory-list").empty();

            //add gif spinner here to show its loading
        },
        success: function (data) {
            if (data != null)
            {
                var items = '<table><tr><th>Name</th><th>Id</th></tr>';
                $.each(data, function (i, item) {
                    //I only added name and Id, but you can add the rest as well
                    items += "<tr><td>" + item.Name + "</td><td>" + item.Id + "</td></tr>";
                });
                items += "</table>";

                //add items to inventory div.
                $("#inventory-list").html(items);
            }
            else
            {
                //show the user that a problem occurred loading the data
                //update inventory-list with an error message
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
});

Then you can define a method in your OrdersController:

然后,您可以在OrdersController中定义一个方法:

[HttpGet]
public JsonResult GetInventoryForStore(int storeId)
{
    var store = db.Store.Find(storeId);

    if (store == null)
        return Json(null, JsonRequestBehavior.AllowGet);

    return Json(store.StoreInventory.ToList(), JsonRequestBehavior.AllowGet);
}

That should about do it. I hope this helps!

应该这样做。我希望这有帮助!

I have not tested the code, so if you see any mistakes, please edit the post.

我没有测试过代码,所以如果你发现任何错误,请编辑帖子。