I'm trying to work out a tag controller for this website I'm working on, but I can't get the json-part to work properly.
To start from the top, I have a hidden input element in my cshtml-view (JS fetched from this SO post):
<input type="hidden" id="tagController" style="width: 350px;" />
...
$(document).ready(function () {
var lastResults = [];
$("#tagController").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
ajax: {
multiple: true,
url: "/UnitDetails/GetTagsAsJson/",
dataType: "json",
type: "POST",
data: function (term, page) {
return {
json: JSON.stringify({ results: [{ id: "foo", text: "foo" }, { id: "bar", text: "bar" }] }),
q: term
};
},
results: function (data, page) {
lastResults = data.results;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function (r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
});
Then, I have an action in my controller:
[HttpPost]
public JsonResult GetTagsAsJson()
{
return Json(Model.TagsAvailable, JsonRequestBehavior.AllowGet);
}
Then, the list TagsAvailable is populated in my index action:
...
foreach (var tag in GetAvailableTags())
{
Model.TagsAvailable.Add(tag.Name);
}
...
Finally, the GetAvailableTags() is calling a wcf service which returns a set of TagContracts in a BaseTagController:
public List<TagContract> GetAvailableTags()
{
return UnitClient.GetAllUnitTags().Select(unitTag => new TagContract
{
Id = unitTag.Id,
Name = unitTag.Name
}).ToList();
}
When inspecting the console in chrome, I get the following error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
For the record, I know for a fact that the service returns the requested data, it's more a problem with the code I've written I guess :)