Reputation: 1233
I have a JsonResult action in my MVC project...
public JsonResult GetData(string term) {
List<String> data = repo.GetData(term).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
This powers a jquery autocomplete lookup but as there is only 30 values in the database, I think that this is not efficent use of database resources...
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("input#MyTextBox").autocomplete({
source: '<%: Url.Action("GetDate","Controller") %>',
delay: 1,
minChars: 2
}
);
});
</script>
I would like to generate something simlar to this...
<script>
$(document).ready(function() {
$("input#MyTextBox").autocomplete({
source: ["my","list","of","values"]
});
});
</script>
I am missing something here as this should be simple. Is there a way that I can change the url.action to something that will render the JSON almost like a PartialView ?
Also, is this a good solution to the problem or can someone show me a better way?
Upvotes: 1
Views: 1723
Reputation: 2356
2 points:
Yes, there is a way to render JSON easier:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("input#MyTextBox").autocomplete({
source: <%: Html.Raw(Json.Encode(Model.AutocompleteSourceFromDb)) %>,
delay: 1,
minChars: 2
}
);
});
</script>
From database usage perspective this doesn't change a thing. You still rendering the whole JSON on page render and not querying database on autocomplete.
Upvotes: 3