Reputation: 1360
I have a controller action which passes in a SQL query result to the view
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
var viewModel = new RegisterViewModel
{
Organisations = _context.Organisations.ToList(),
};
ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}
The view is a registration page which asks for the users email address. I want the email address to autofill with the domain relevant to their organisation after they type "@" - this is facilitated by jquery.email-autocomplete.js - Example image of input field in use: here
There are about 50 organisations and they are stored in a database table which is structured like:
ID | Name | EmailDomain
-----------------------------------
1 My Org myorganisation.co.uk
I need a way to dynamically get the email domains from the organisation object into this bit of jquery code in the view:
<script>
$("#email").emailautocomplete({
suggClass: "custom-classname", //default: "eac-sugg". your custom classname (optional)
domains: ["example.com"] //additional domains (optional)
});
</script>
So when rendered, the line of code for domains needs to look something like:
domains: ["myorganisation.co.uk", "anotherorganisation.org.uk", "andanother.com"]
Upvotes: 0
Views: 407
Reputation: 1360
This is what I ended up doing
$("#email").emailautocomplete({
domains: [@foreach (var organisation in Model.Organisations)
{
@Html.Raw("\"") @organisation.EmailDomain
@Html.Raw("\", \r\n")
}
@Html.Raw("]")
});
Which renders as:
$("#Email").emailautocomplete({
domains: ["domain1.gov.uk",
"domain2.com",
"domain3.gov.uk",
"domain4.gov.uk",
]
});
Upvotes: 0
Reputation: 277
You need an action result in your controller to handle the autocomplete. Something like:
public ActionResult AutocompleteEmail(string text)
{
var filteredItems = MethodToLookupDBValues(text);
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}
You can then call it from js like so:
$('#email').autocomplete({
source: function (request, response) {
$.getJSON('@Url.Action("AutocompleteEmail")', {
text: request.term
}, response);
},
select: function (event, ui) {
$('#selectedItem').val(ui.item.id);
}
});
Upvotes: 1