问题
I'm looking for a way to populate the Magic Suggest control with multiple values. I am using ASP.NET MVC and would like to set these values based on properties in the model.
Part 1: Magic Suggest Support for Multiple Values? A related question on SOF addresses adding a single value but not multiple. Is this possible?
Part 2: Ideally, I'd like to bind the control the MVC model somehow. If this is not possible, I'd at least like to set the pre-selected values dynamically. I have access the model via razor syntax. Something similar to how Magic Suggest allows you to set the data perhaps.
$(function () {
$('#magicsuggest').magicSuggest({
data: '/controller/GetValuesJson?mealId=@Model.Id',
valueField: 'Id',
displayField: 'Name',
/* The property below allows pre-selection */
/* How can I use Razor and set from my MVC model?* /
value: */ Some Code Here */
});
});
EDIT: Part 2: Attempting to set the value property by any variable seems to fail. I've tried variations of strings, quotes etc. to no avail.
var returnedIds = [1,2]; // Or some variable population
$(function () {
$('#magicsuggest').magicSuggest({
data: '/controller/GetValuesJson?mealId=@Model.Id',
valueField: 'Id',
displayField: 'Name',
value: [returnedIds]
});
});
Solved: Thanks to @karlipoppins posts below and some tinkering.
$(function ()
{
$.ajax({
url: '@Url.Action("GetSomeValuesJson")',
data: { Id: 1},
type: 'post',
success: function (returnedVal)
{
var ms = $('#magicsuggest').magicSuggest(
{
data: '/Meal/GetSomeValuesJson?&Id=@Model.Id',
valueField: 'Id',
displayField: 'Name',
});
ms.setValue(returnedVal);
}
});
});
回答1:
From what I understand you are trying to set multiple values when the component is loaded up. On your code you are using Id
as the value field and Name
as the displayField.
This means that magicsuggest is expecting data
to be in the form of
[{"Id": 1, "Name": "hello"}, {"Id": 2, "Name": "world"}, {"Id": 3, "Name": "no"}]
Now to set multiple values, you can
1) do that when defining the component in js:
$('#magicsuggest').magicSuggest({
data: '/controller/GetValuesJson?mealId=@Model.Id',
valueField: 'Id',
displayField: 'Name',
value: [1, 2] // select 'hello', 'world'
});
2) or you can also define it directly in your DOM containing field:
<div id="magicsuggest" value="[1,2]"></div>
and then create the component like this:
$('#magicsuggest').magicSuggest({
data: '/controller/GetValuesJson?mealId=@Model.Id',
valueField: 'Id',
displayField: 'Name'
});
See both examples here: http://jsfiddle.net/Kpz6y/
Cheers
来源:https://stackoverflow.com/questions/23942871/magic-suggest-pre-select-multiple-items-from-mvc-model