add item to c# list on selectchange loaded through cascading

五迷三道 提交于 2020-06-29 04:28:26

问题


i have selectList with multiple attr which is filled through cascading(on select a company i just show selected Company Models) Now i want to allow user to select multiple models such that on select, item should add in c# list and display in page and then allow user to select more of any other company.Picture attached Following is my code. OrderViewModel

      public class OrderViewModel
      {
        [Display(Name ="Order ID")]
        public int order_id { get; set; }
        [Required]

        public string cus_name { get; set; }
        public string cus_phone { get; set; } 
        public System.DateTime Date { get; set; }
        [DataType(DataType.Date)]
        public System.DateTime Date { get; set; }
        public int Amount { get; set; }
        public List<Products> Products { get; set; }

      }

i want to bind selected Item in 'Products' List of OrderViewModel which will be send to server with Further fields. Products

public class Products
{
    public int id { get; set; }
    public int modelId { get; set; }
    public int Phoneid { get; set; }
    public int Quantity { get; set; }
    public double price { get; set; }
    public bool isSelected { get; set; }
    public int order_id { get; set; }
}

Razor View

 <div class="form-group row">
                <label  class="control-label col-6">Company Name</label>
                <div class="col-12">
                    <select id="CompanyId"  class="custom-select mr-sm-2"
                            asp-items="@(new SelectList( @ViewBag.Companies,"Phoneid","Com_name"))">
                        <option value="">Please Select</option>
                    </select>
                </div>
                <span  class="text-danger"></span>
            </div>
            <div class="form-group row">
                <label  class="control-label col-6"></label>
                <div class="col-12">
                    <select id="modelId" multiple class="custom-select mr-sm-2"
                            asp-items="@(new SelectList(string.Empty,"modelId","model_name","--Select--"))">
                        <option value="">Please Select</option>
                    </select>
                </div>
                <span class="text-danger"></span>
            </div>

what i have tried yet to add item in list

 <script>
                $("#modelId").change(function () {
                    var list = @(Model.Products);
                    let item = $(this).children("option:selected").val();

                    list.forEach(x => {
                        if (x.modelId != item) {

                            @{ 

                                Products products = new Products()
                                {
                                    isSelected=true,
                                    modelId= item,
                                };
                                Model.Products.Add(products);
                            }
                        }
                    });
                })
                 @for (int i = 0; i < Model.Products.Count; i++)
                 {

                 }
            </script>

I display all selected product throught partial view now i just want to send these selected products along with Quanity and Price of each to Server


回答1:


Here is a working demo like below:

Model:

public class Model
{
    [Key]
    public int modelId { get; set; }
    [Display(Name = "Model Name")]
    public string model_name { get; set; }
    public int Phoneid { get; set; }
    public IList<Products> Products { get; set; }
}
public class Company
{
    [Key]
    public int Phoneid { get; set; }
    [Display(Name = "Company Name")]
    public string Com_name { get; set; }
}
public class Products
{
    public int id { get; set; }
    public int modelId { get; set; }
    public int Phoneid { get; set; }
    public int Quantity { get; set; }
    public double price { get; set; }
    public bool isSelected { get; set; }
    public int order_id { get; set; }
}

View(Index.cshtml):

@model Products
<div>
    <div style="float:left;width:40%">
        <form id="form">
            <div class="form-group row">
                <label>Company Name</label>
                <div class="col-12">
                    <select id="CompanyId" asp-for="Phoneid" class="custom-select mr-sm-2"
                            asp-items="@(new SelectList( @ViewBag.Companies,"Phoneid","Com_name"))">
                        <option value="">Please Select</option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label>Model Name</label>
                <div class="col-12">
                    <select id="modelId" multiple class="custom-select mr-sm-2" name="modelId"
                            asp-items="@(new SelectList(string.Empty,"modelId","model_name","--Select--"))">
                        <option value="">Please Select</option>
                    </select>
                </div>                
            </div>
            <div>
                <input type="button" id="saveBtn" value="Save" />
            </div>
        </form>

    </div>
    <div style="float:right;width:60%">
        <h5>Products</h5>
        <div id="products"></div>
    </div>
</div>

@section Scripts
{
    <script>
    $(function () {
        $('#CompanyId').change(function () {  
            var data = $("#CompanyId").val();
            console.log(data);
            $.ajax({
                url: '/Home/GetModel?Phoneid=' + $("#CompanyId").val(),
                type: 'Get',
                success: function (data) { 
                    var items = "<option value='0'>Select</option>";
                    $.each(data, function (i, item) {
                        items += "<option value='" + item.value + "'>" + item.text + "</option>";
                    });
                    $('#modelId').html(items);

                }
            })
        });
        $('#saveBtn').click(function () {
            $.ajax({
                url: '/Home/GetProduct?Phoneid=' + $("#CompanyId").val() + "&modelId=" + $('#modelId').val(),
                type: 'Post',
                success: function (data) {
                    $('#products').html(data);
                }
            })
        })                   
    })

    </script>
}

Partial View(_Partial.cshtml):

@model IEnumerable<Products>
<table class="table">
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>check</td>
                <td>
                    <input asp-for="@item.isSelected" />
                </td>
                <td>Product Id</td>
                <td>
                    @Html.DisplayFor(modelItem => item.id)
                </td>
            </tr>
            <tr>
                <td>Quantity</td>
                <td>
                    @Html.DisplayFor(modelItem => item.Quantity)
                </td>
                <td>Price</td>
                <td>
                    @Html.DisplayFor(modelItem => item.price)
                </td>
            </tr>
        }
    </tbody>
</table>

Controller:

public class HomeController : Controller
{
    private readonly MvcProj3Context _context;
    public HomeController(MvcProj3Context context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        ViewBag.Companies = _context.Company.ToList();
        return View();
    }
    public JsonResult GetModel(int Phoneid)
    {
        List<Model> model = new List<Model>();
        model = (from m in _context.Model
                 where m.Phoneid == Phoneid
                 select m).ToList();
        return Json(new SelectList(model, "modelId", "model_name"));
    }
    [HttpPost]
    public IActionResult GetProduct(int Phoneid, string[] modelId)
    {
        var data = new List<Products>();
        var ids = modelId[0].Split(',');
        foreach(var item in ids)
        {
            var id = int.Parse(item);
            //guess the modelA in CompanyA contains several products
            var product = (from p in _context.Products
                            where p.Phoneid == Phoneid && p.modelId == id
                            select p).ToList();
            foreach (var pro in product)
            {
                data.Add(pro);
            }
        }
        return PartialView("_Partial", data);
    }
}

Result:



来源:https://stackoverflow.com/questions/61962733/add-item-to-c-sharp-list-on-selectchange-loaded-through-cascading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!