Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - Select2 Not getting value of selected items

I have an select2 list in an edit form and it does not seem to be holding the selected value. I thought that this was working at one point but not sure. The mselect works fine for selecting and they are visable on the form, however when I go to save, the value is null.

Below is my javascript:

<script type="text/javascript">

$(document).ready(function () {
   
var select=    $('.mselect').select2({
        ajax: {
            url: '/Parts/GetPartsBySearch',
            width: 'resolve',
            data: function (params) {
                return {
                    q: params.term// search term
                };
            },
            processResults: function (data) {
                return {
                    results: data.items
                };
            },
            minimumInputLength: 2,
            width: 'resolve'
        }
    });

    var model = '@Html.Raw(Json.Encode(Model.SelectedParts))';

    $(".mselect").val(JSON.parse(model)).trigger('change');
})

This is the input for that:

<div class="col-md-4">
   <div class="form-group">
      @Html.LabelFor(model => model.SelectedParts, htmlAttributes: new { @class = "control-label" })<br />
      @Html.DropDownListFor(model => model.SelectedParts, new SelectList(Model.PartsNum, "Value", "Text"), new { @class = "form-control mselect", multiple = "true" })
      @Html.ValidationMessageFor(model => model.SelectedParts, "", new { @class = "text-danger" })
   </div>
</div>

The Model:

 public string[] SelectedParts { get; set; }

Although I do not believe the controller has anything to do with it here is my post for the that part:

 foreach (var item in model.SelectedParts)
 {
    ProductMaster prodMast = new ProductMaster
    {
      ProductMasterId = Guid.NewGuid(),
      Material = Guid.Parse(item),
      VendorId = model.VendorId,
      CreatedBy = userId,
      CreatedDate = System.DateTime.Now
    };

    db.ProductMaster.Add(prodMast);
    db.SaveChanges();
 }

So Model.SelectedParts is null.

Also I am using JQuery Version 3.4.1

Thanks for your help!

UPDATE: I am thinking there is an issue with the select2 and the @Html.DropdownListFor I am not seeing a value in the console window. The value is actually in the <option></option> tags and not for the id mselect

question from:https://stackoverflow.com/questions/65892561/select2-not-getting-value-of-selected-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...