0

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

enter image description here

Muhammad Sami
  • 520
  • 2
  • 8
  • 21

1 Answers1

2

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: enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72
  • i want to bind selected Item in 'Products' List of OrderViewModel which will be send to server with Further fields.How to add Selected items in Products List – Muhammad Sami May 25 '20 at 13:02
  • another problem is when you select com1 data then it is rendered by partial view but when render com2 data. com1 data got clear. i wanna show both previous com selected data as well as new selected data – Muhammad Sami May 25 '20 at 17:03
  • Please share your whole model with the relationship.And what do you mean for add selected items in product list?What are the selected items? – Rena May 26 '20 at 08:15
  • actually i am working on order page. i already share my orderViewModel. i want to allow user to select multiple item throught select and then bind it ProductList of OrderViewModel with other fields like customer name,Date etc. OrderViewModel has One to Many relationship with Products as each order can have multiple orders(mean there is list of Products in each Order). Selected Item means Items which is selected through select. i want to add selected items( which User selects through select of models) in Products List of OrderViewModel. – Muhammad Sami May 26 '20 at 08:27
  • `i want to allow user to select multiple item throught select and then bind it ProductList of OrderViewModel with other fields like customer name,Date etc. `-Did you mean that when you select the two selectlist and it could display the product list which is related with OrderViewModel.Anotherway is to say,you want to display the OrderViewModel??`Selected Item means Items which is selected through select.`-So,you want to add the company name and model name to the Products list?Which property in your product list match these properties. – Rena May 26 '20 at 08:42
  • Your requirement is a bit in a mess.Please explain more.Actually,I have done what your picture shown.I think you could try to draw a picture to explain what you want. – Rena May 26 '20 at 08:44
  • Image Updated, Example Scenario, User Open Order Page, He fill his details like name,phone etc then he select company and models through select then save it so we display selected items throught partial view. Now whatever Products user selected, i want to send these products along customer data to server. for this, i created Product list in orderViewModel which contains List of Products which user Select. So the only problem i am facing is in binding selectedItems in Products property of OrderViewModel. – Muhammad Sami May 26 '20 at 10:17
  • Post Updated. Please help me still unable to solve this issue – Muhammad Sami May 29 '20 at 10:44