I'm trying to bind value from select2 list to model on post razor mvc
I fixed this by removing:
initSelection: function (element, callback) {
var data= { id: @Model.PartId.ToString(), text: '@Model.PartsList.Where(x=> x.Id == Model.PartId.ToString() ).First().Text'};
callback(data);
}
and using the following (currently it selects option 99 but I can replace this with the PartId from the model.
$('#selectpicker1').val('99');
$('#selectpicker1').trigger('change');
MVC 5 Dropdownlistfor multiselect value binding in edit view
Since you have item values provided in ViewBag
definition like this, which clearly indicates string values:
ViewBag.ItemsBag = db.Items.Select(v => new SelectListItem
{
Text = v.ItemName,
Value = v.ItemId.ToString() // implies all values are strings
});
Then the property to bound with DropDownListFor
/ListBox
must have List<string>
or string[]
type to be bound properly. Using ICollection<Item>
will not bound because it is a complex object, while the helper requires value types (numeric types/string) to bound with.
Hence, you must create a property with type List<string>
first:
public List<string> SelectedValues { get; set; }
And then use ListBoxFor
helper with that property instead:
@Html.ListBoxFor(model => model.SelectedValues, new MultiSelectList(ViewBag.ItemsBag, "Value", "Text", Model.ItemsSelected.Select(x => x.Value)), new { @class = "form-control features-segments select2-multiselect-checkbox", multiple = "multiple" })
Note:
If ItemId
property has int
type (and all values are convertible to int
), try with List<int>
/int[]
type instead of List<string>
/string[]
:
public List<int> SelectedValues { get; set; }
How to binding Select2 to string array tags?
Do you mean you want to fill select with the value of Words?If so,you can use asp-items to set options of select.Also,you can pass other list to view,and fill select
.Here is a demo to fill select
with Model.Words
:
Model:
public class Product
{
public List<string> Words { get; set; }
}
Action:
public IActionResult TestProduct() {
return View(new Product { Words=new List<string> { "aa","bb","cc"} });
}
View:
<select asp-for="Words" class="form-control " multiple="multiple" asp-items="@Model.Words.Select(x=>new SelectListItem { Text=x,Value=x})"></select>
$("#@Html.IdFor(m=>m.Words)").select2({
tags: true
});
result:
How to set the values selected in select2 list box in MVC application when i want edit the data
Please check the working example here you need to replace this code with your functionality.
var values = "1,3";$('#example').val(values.split(','));$('#example').select2().trigger('chnage');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" integrity="sha256-FdatTf20PQr/rWg+cAKfl6j4/IY3oohFAJ7gVC3M34E=" crossorigin="anonymous" /><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js" integrity="sha256-d/edyIFneUo3SvmaFnf96hRcVBcyaOy96iMkPez1kaU=" crossorigin="anonymous"></script>
<select id="example" multiple="multiple" style="width: 300px"> <option value="1">A</option> <option value="2">Youvalue</option> <option value="3">Yourvalue </option></select>
Bind Razor TextArea to Model class attribute
There are ways of doing this with nicer UI (this might get you started: Passing the collection of selected values from a Select2-Multi DropDownList to a Controller)
But to answer your exact question: Use a string property in your ViewModel to "wrap" the List property.
public class MyViewModel
{
public List<string> MyList { get; set; }
public string MyListAsString
{
get
{
return string.Join(",", MyList);
}
set
{
MyList = value.Split(new char[] { ',' }).Select(x => x.Trim()).ToList();
}
}
}
In your razor view, don't use MyList anywhere -- use MyListAsString, which will get and set MyList when the ModelBinder does its things.
@Html.TextAreaFor(model => model.MyListAsString,
htmlAttributes: new { @class = "control-label col-md-2" })
(Best practises: I have renamed your List property to MyList, so as not to reuse an existing identifier. And you probably don't want to use "control-label" class on something that isn't a label. Try "form-control")
Dropdowns on Edit Page Won't Retain Value if Not Re-Selected
In order to retain the values of the dropdowns when making ANY change to the edit page, one simply needs to remove this bit of HTML from each of the dropdown's code:
disabled="@(item1.ID.ToString()==Model.InfoSite.Specialty?true:false)"
@Html.ListBoxFor usage and creation questions
1) How to definite the property for the selected list? @Html.ListBoxFor(x => x.SelectedOptions, new MultiSelectList(Model.SelectedOptionList), new { id = "list2", Multiple = "multiple", Size = 15, style = "width: 100%;" })
2) How to have a initial empty list (for list2)? list1 has populated items.
In controller set an empty list testModel.SelectedOptionList = new List<SelectListItem>();
3) How to return all of list2 items to model when submit button is clicked
Probably you need to set all the items in list2 as selected (using jquery) before submitting. All the selected items in list2 items will bind to TestModel.SelectedOptions on submit.
Related Topics
Declare Properties to Ignore in Entities Interface (Ef Core)
Lambda Where Id Does Not Exist in Another List
How to Call a Button Click Event from Another Method
Multidimensional Array from a Txt File
Itextsharp Pdfptable How to Make a Border Around Entire Table
How to Trim All Elements in a List
How to Provide Success Messages ASP.NET MVC
How to Determine If .Net Core Is Installed
How to Add a Run Button and Compile Button on the Toolbar in Visual Studio
How to Directly Print a Report Without Going Through Crystal Reports Viewer
Reading Large Text Files With Streams in C#
How to Get the Specific Column in Excel Worksheet Using Documentformat.Openxml C#
How to Delete All Files in an Azure File Storage Folder
Configurationmanager.Appsettings Getting Null
Take String Before and After 'First' Space Character