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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…